Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

328 linesCodeBlameRaw
1//! A workspace's single sign-on, over REST and MCP: its connection to the
2//! workspace's identity provider (OpenID Connect, OAuth 2.0 or SAML 2.0),
3//! requiring it of members, the people linked to it, and unlinking one.
4//! Identity decides and keeps all of it (services/identity/src/sso.rs);
5//! owners only, as people, and setting it up needs a paid plan. Signing in
6//! through it is a browser's trip to the provider, so it is not here.
7
8use g1t_contracts::sso::{ScimToken, SsoConfig, SsoProtocol, SsoSettings, sso_addresses};
9use g1t_contracts::{FailureCode, Outcome, Viewer};
10use serde_json::{Value, json};
11use worker::Result;
12
13use crate::operations::Services;
14
15/// One operation.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum SsoOp {
18 GetSso,
19 ConfigureSso,
20 SetSsoRequired,
21 DeleteSso,
22 ListSsoIdentities,
23 UnlinkSsoIdentity,
24 EnableScim,
25 DisableScim,
26}
27
28/// The config fields an owner sends, as `SsoConfig` names them.
29const CONFIG_FIELDS: [&str; 10] = [
30 "issuer",
31 "client_id",
32 "scopes",
33 "authorization_url",
34 "token_url",
35 "userinfo_url",
36 "subject_claim",
37 "email_claim",
38 "idp_entity_id",
39 "idp_sso_url",
40];
41
42impl SsoOp {
43 /// Every one: `Op::ALL` lists each as `Op::Sso(…)`, which a test checks
44 /// against this.
45 #[cfg(test)]
46 pub const ALL: [SsoOp; 8] = [
47 SsoOp::GetSso,
48 SsoOp::ConfigureSso,
49 SsoOp::SetSsoRequired,
50 SsoOp::DeleteSso,
51 SsoOp::ListSsoIdentities,
52 SsoOp::UnlinkSsoIdentity,
53 SsoOp::EnableScim,
54 SsoOp::DisableScim,
55 ];
56
57 pub fn name(self) -> &'static str {
58 match self {
59 SsoOp::GetSso => "get_sso",
60 SsoOp::ConfigureSso => "configure_sso",
61 SsoOp::SetSsoRequired => "set_sso_required",
62 SsoOp::DeleteSso => "delete_sso",
63 SsoOp::ListSsoIdentities => "list_sso_identities",
64 SsoOp::UnlinkSsoIdentity => "unlink_sso_identity",
65 SsoOp::EnableScim => "enable_scim",
66 SsoOp::DisableScim => "disable_scim",
67 }
68 }
69
70 pub fn title(self) -> &'static str {
71 match self {
72 SsoOp::GetSso => "Get a workspace's single sign-on",
73 SsoOp::ConfigureSso => "Set up or change a workspace's single sign-on",
74 SsoOp::SetSsoRequired => "Require single sign-on, or stop",
75 SsoOp::DeleteSso => "Remove a workspace's single sign-on",
76 SsoOp::ListSsoIdentities => "List the people linked through single sign-on",
77 SsoOp::UnlinkSsoIdentity => "Unlink someone from single sign-on",
78 SsoOp::EnableScim => "Turn on SCIM, or make a new SCIM token",
79 SsoOp::DisableScim => "Turn off SCIM",
80 }
81 }
82
83 pub fn description(self) -> &'static str {
84 match self {
85 SsoOp::GetSso => "A workspace's single sign-on through its own identity provider: connection (null when it has none: its id, protocol oidc, oauth2 or saml, config with the protocol's fields, has_client_secret, certificates by SHA-256 fingerprint for SAML, allow_join, tested_at and tested_by, when the first person signed in through it), required (whether members must sign in through it), you_linked (whether you have), identities (the people linked: username, subject and email at the provider, linked_at, last_used_at), and service_provider: the addresses to give the provider (redirect_uri for OpenID Connect and OAuth 2.0; entity_id, acs_url and metadata_url for SAML; sign_in_url, where people start). The client secret is never returned. Owners only, as people.",
86 SsoOp::ConfigureSso => "Set up the workspace's single sign-on, or change it, with every field of the protocol. oidc: issuer (read for its discovery document first), client_id, client_secret, scopes (openid email profile by default). oauth2: authorization_url, token_url, userinfo_url, client_id, client_secret, scopes, subject_claim (sub, then id, by default) and email_claim (email). saml: idp_entity_id, idp_sso_url and certificate (the provider's signing certificates, PEM; several while rotating). client_secret and certificate left out keep what is saved. allow_join (true by default) lets anyone the provider signs in join as a member. Moving to another provider (protocol, issuer or entity id) unlinks everyone and stops requiring it. Needs a paid plan. Returns what get_sso does. Recorded as sso.created or sso.updated. Owners only, as people.",
87 SsoOp::SetSsoRequired => "Whether members must sign in through the provider: then a member uses the workspace only from a session that did in the last day, and with tokens and keys once linked; held out otherwise, keeping their place. Owners are never held, and outside collaborators are not asked. Requiring it needs a paid plan and you to have signed in through it yourself (you_linked); stopping never does. Recorded as sso.required or sso.not_required. Owners only, as people.",
88 SsoOp::DeleteSso => "Remove the workspace's single sign-on: forgets the provider and who everyone is there, and stops requiring it. Members keep their place. Never needs a plan. Recorded as sso.deleted. Owners only, as people.",
89 SsoOp::ListSsoIdentities => "The people linked to the workspace's provider: username, subject (their id at the provider), email (as the provider gave it, for showing), linked_at and last_used_at. Owners only, as people.",
90 SsoOp::EnableScim => "Turn on SCIM for the workspace's single sign-on, or replace its token: returns token (shown this once; the old one stops working), hint (its last four characters) and scim_url, the SCIM 2.0 base URL to give the identity provider with the token as a bearer token. With SCIM on, only people the provider has assigned (active users) can sign in through single sign-on, and one it deactivates or deletes leaves the workspace at once: membership, roles, link and sessions. Owners are never removed that way. Users only; groups are not kept. Needs single sign-on set up and a paid plan. Recorded as sso.scim_enabled or sso.scim_token_rotated. Owners only, as people.",
91 SsoOp::DisableScim => "Turn off SCIM: the token stops working and the provisioned users are forgotten. Nobody is removed from the workspace, and single sign-on lets people in as before. Recorded as sso.scim_disabled. Owners only, as people.",
92 SsoOp::UnlinkSsoIdentity => "Forget who someone is at the workspace's provider, so they (or another account there) link again on their next sign-in through it; their sessions go through it again. Recorded as sso.identity_unlinked. Owners only, as people.",
93 }
94 }
95
96 /// Whether it changes anything: checked against the scope table in tests.
97 #[cfg(test)]
98 pub fn writes(self) -> bool {
99 !matches!(self, SsoOp::GetSso | SsoOp::ListSsoIdentities)
100 }
101
102 pub fn input(self) -> Value {
103 let workspace = json!({ "type": "string", "description": "The workspace's name, e.g. \"acme\"." });
104 let (properties, required): (Value, &[&str]) = match self {
105 SsoOp::GetSso | SsoOp::DeleteSso | SsoOp::ListSsoIdentities | SsoOp::EnableScim | SsoOp::DisableScim => (json!({ "workspace": workspace }), &["workspace"]),
106 SsoOp::ConfigureSso => (
107 json!({
108 "workspace": workspace,
109 "protocol": { "type": "string", "enum": ["oidc", "oauth2", "saml"], "description": "How g1t speaks to the provider." },
110 "issuer": { "type": "string", "description": "oidc: the issuer, where its /.well-known/openid-configuration lives." },
111 "client_id": { "type": "string", "description": "oidc, oauth2: the client id." },
112 "client_secret": { "type": "string", "description": "oidc, oauth2: the client secret; kept encrypted, never returned. Left out keeps the one saved." },
113 "scopes": { "type": "string", "description": "oidc, oauth2: space-separated scopes." },
114 "authorization_url": { "type": "string", "description": "oauth2: the authorization endpoint (https)." },
115 "token_url": { "type": "string", "description": "oauth2: the token endpoint (https)." },
116 "userinfo_url": { "type": "string", "description": "oauth2: the userinfo endpoint (https)." },
117 "subject_claim": { "type": "string", "description": "oauth2: the userinfo claim that is the person's stable id; a dotted path works." },
118 "email_claim": { "type": "string", "description": "oauth2: the userinfo claim that is their address." },
119 "idp_entity_id": { "type": "string", "description": "saml: the provider's entity id (its issuer)." },
120 "idp_sso_url": { "type": "string", "description": "saml: where the provider takes requests (HTTP-Redirect, https)." },
121 "certificate": { "type": "string", "description": "saml: the provider's signing certificates, PEM. Left out keeps the ones saved." },
122 "allow_join": { "type": "boolean", "description": "Anyone the provider signs in joins as a member. True by default." },
123 }),
124 &["workspace", "protocol"],
125 ),
126 SsoOp::SetSsoRequired => (
127 json!({
128 "workspace": workspace,
129 "required": { "type": "boolean", "description": "True to require it of members; false to stop." },
130 }),
131 &["workspace", "required"],
132 ),
133 SsoOp::UnlinkSsoIdentity => (
134 json!({
135 "workspace": workspace,
136 "username": { "type": "string", "description": "Whose link to forget." },
137 }),
138 &["workspace", "username"],
139 ),
140 };
141 json!({ "type": "object", "properties": properties, "required": required })
142 }
143}
144
145fn text(input: &Value, key: &str) -> Option<String> {
146 match &input[key] {
147 Value::String(text) if !text.trim().is_empty() => Some(text.trim().to_owned()),
148 _ => None,
149 }
150}
151
152fn flag(input: &Value, key: &str) -> Option<bool> {
153 match &input[key] {
154 Value::Bool(value) => Some(*value),
155 Value::String(text) => match text.trim() {
156 "true" | "1" => Some(true),
157 "false" | "0" => Some(false),
158 _ => None,
159 },
160 _ => None,
161 }
162}
163
164/// The protocol's fields as sent: the config, its secret and certificate.
165fn config_of(input: &Value) -> SsoConfig {
166 let mut config = json!({});
167 for field in CONFIG_FIELDS {
168 if let Some(value) = text(input, field) {
169 config[field] = json!(value);
170 }
171 }
172 serde_json::from_value(config).unwrap_or_default()
173}
174
175/// The settings, with where to point the provider.
176fn with_addresses(settings: SsoSettings, site: &str, api: &str) -> Value {
177 let addresses = sso_addresses(site, &settings.slug);
178 let mut out = serde_json::to_value(&settings).unwrap_or_default();
179 out["service_provider"] = serde_json::to_value(addresses).unwrap_or_default();
180 out["service_provider"]["scim_url"] = json!(scim_url(api, &settings.slug));
181 out
182}
183
184/// The SCIM 2.0 base URL for a workspace (scim.rs).
185fn scim_url(api: &str, slug: &str) -> String {
186 format!("{}/scim/v2/{}", api.trim_end_matches('/'), slug.to_lowercase())
187}
188
189pub async fn run(op: SsoOp, services: &Services, viewer: &Viewer, input: &Value) -> Result<Outcome<Value>> {
190 let Some(actor) = viewer.clone() else {
191 return Ok(Outcome::fail(FailureCode::Unauthenticated, "This needs a g1t access token."));
192 };
193 let Some(workspace) = text(input, "workspace").map(|w| w.to_lowercase()) else {
194 return Ok(Outcome::fail(FailureCode::Invalid, "Name the workspace."));
195 };
196 let identity = &services.identity;
197 let surface = services.audit.surface;
198 let site = services.addresses.site.as_str();
199 let api = services.addresses.api.as_str();
200 let settings = |outcome: Outcome<SsoSettings>| match outcome {
201 Outcome::Ok(settings) => Outcome::Ok(with_addresses(settings, site, api)),
202 Outcome::Fail(failure) => Outcome::Fail(failure),
203 };
204 Ok(match op {
205 SsoOp::GetSso => settings(g1t_kit::call(identity, "sso_settings", &json!({ "actor": actor, "slug": workspace })).await?),
206 SsoOp::ListSsoIdentities => {
207 let found: Outcome<SsoSettings> = g1t_kit::call(identity, "sso_settings", &json!({ "actor": actor, "slug": workspace })).await?;
208 match found {
209 Outcome::Ok(found) => Outcome::Ok(serde_json::to_value(found.identities).unwrap_or_default()),
210 Outcome::Fail(failure) => Outcome::Fail(failure),
211 }
212 }
213 SsoOp::ConfigureSso => {
214 let Some(protocol) = text(input, "protocol").as_deref().and_then(SsoProtocol::parse) else {
215 return Ok(Outcome::fail(FailureCode::Invalid, "protocol is oidc, oauth2 or saml."));
216 };
217 if input.get("allow_join").is_some_and(|v| !v.is_null()) && flag(input, "allow_join").is_none() {
218 return Ok(Outcome::fail(FailureCode::Invalid, "allow_join is true or false."));
219 }
220 let saved: Outcome<SsoSettings> = g1t_kit::call(
221 identity,
222 "save_sso",
223 &json!({
224 "actor": actor,
225 "slug": workspace,
226 "protocol": protocol,
227 "config": config_of(input),
228 "client_secret": text(input, "client_secret"),
229 "certificate": text(input, "certificate"),
230 "allow_join": flag(input, "allow_join").unwrap_or(true),
231 "surface": surface,
232 }),
233 )
234 .await?;
235 settings(saved)
236 }
237 SsoOp::SetSsoRequired => {
238 let Some(required) = flag(input, "required") else {
239 return Ok(Outcome::fail(FailureCode::Invalid, "required is true or false."));
240 };
241 let set: Outcome<bool> = g1t_kit::call(
242 identity,
243 "set_sso_required",
244 &json!({ "actor": actor, "slug": workspace, "required": required, "surface": surface }),
245 )
246 .await?;
247 match set {
248 Outcome::Ok(required) => Outcome::Ok(json!({ "required": required })),
249 Outcome::Fail(failure) => Outcome::Fail(failure),
250 }
251 }
252 SsoOp::DeleteSso => {
253 let removed: Outcome<bool> =
254 g1t_kit::call(identity, "delete_sso", &json!({ "actor": actor, "slug": workspace, "surface": surface })).await?;
255 match removed {
256 Outcome::Ok(removed) => Outcome::Ok(json!({ "deleted": removed })),
257 Outcome::Fail(failure) => Outcome::Fail(failure),
258 }
259 }
260 SsoOp::EnableScim => {
261 let made: Outcome<ScimToken> =
262 g1t_kit::call(identity, "enable_scim", &json!({ "actor": actor, "slug": workspace, "surface": surface })).await?;
263 match made {
264 Outcome::Ok(made) => Outcome::Ok(json!({ "token": made.token, "hint": made.hint, "scim_url": scim_url(api, &workspace) })),
265 Outcome::Fail(failure) => Outcome::Fail(failure),
266 }
267 }
268 SsoOp::DisableScim => {
269 let off: Outcome<bool> =
270 g1t_kit::call(identity, "disable_scim", &json!({ "actor": actor, "slug": workspace, "surface": surface })).await?;
271 match off {
272 Outcome::Ok(off) => Outcome::Ok(json!({ "disabled": off })),
273 Outcome::Fail(failure) => Outcome::Fail(failure),
274 }
275 }
276 SsoOp::UnlinkSsoIdentity => {
277 let Some(username) = text(input, "username") else {
278 return Ok(Outcome::fail(FailureCode::Invalid, "Name the person to unlink."));
279 };
280 let unlinked: Outcome<bool> = g1t_kit::call(
281 identity,
282 "unlink_sso_identity",
283 &json!({ "actor": actor, "slug": workspace, "username": username, "surface": surface }),
284 )
285 .await?;
286 match unlinked {
287 Outcome::Ok(unlinked) => Outcome::Ok(json!({ "unlinked": unlinked })),
288 Outcome::Fail(failure) => Outcome::Fail(failure),
289 }
290 }
291 })
292}
293
294#[cfg(test)]
295mod tests {
296 use super::*;
297 use g1t_contracts::scopes::{Level, scope_for};
298
299 #[test]
300 fn each_operation_is_described_and_scoped() {
301 for op in SsoOp::ALL {
302 assert!(crate::operations::Op::ALL.contains(&crate::operations::Op::Sso(op)), "{}", op.name());
303 assert!(!op.title().is_empty() && op.description().len() > 40, "{}", op.name());
304 assert!(op.input()["required"].as_array().unwrap().contains(&json!("workspace")), "{}", op.name());
305 let level = scope_for(op.name()).unwrap().level();
306 assert_eq!(level == Level::Read, !op.writes(), "{}", op.name());
307 }
308 }
309
310 #[test]
311 fn only_the_protocols_fields_are_sent() {
312 let config = config_of(&json!({ "issuer": " https://acme.okta.com ", "client_id": "c", "client_secret": "s", "certificate": "pem", "nonsense": "x", "scopes": "" }));
313 assert_eq!(config.issuer.as_deref(), Some("https://acme.okta.com"));
314 assert_eq!(config.client_id.as_deref(), Some("c"));
315 assert_eq!(config.scopes, None);
316 assert!(config.certificates.is_empty());
317 }
318
319 #[test]
320 fn the_answer_says_where_to_point_the_provider() {
321 let settings = SsoSettings { slug: "acme".into(), connection: None, required: false, you_linked: false, identities: vec![], scim: None };
322 let out = with_addresses(settings, "https://g1t.sh", "https://api.g1t.sh");
323 assert_eq!(out["service_provider"]["scim_url"], "https://api.g1t.sh/scim/v2/acme");
324 assert_eq!(out["service_provider"]["acs_url"], "https://g1t.sh/auth/sso/acme/saml");
325 assert_eq!(out["service_provider"]["redirect_uri"], "https://g1t.sh/auth/sso/acme/callback");
326 assert_eq!(out["connection"], Value::Null);
327 }
328}