diff --git a/Cargo.lock b/Cargo.lock index c99e5393..396e3514 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4796,6 +4796,7 @@ version = "0.5.14" dependencies = [ "anyhow", "async-trait", + "aws-lc-rs", "base64 0.23.1", "chrono", "cookie", @@ -4915,6 +4916,7 @@ version = "0.5.14" dependencies = [ "async-bb8-diesel", "async-trait", + "base64 0.23.1", "bb8", "chrono", "diesel", diff --git a/Cargo.toml b/Cargo.toml index 4036ae5f..5475e84f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ version = "0.5.14" anyhow = "1.0" async-bb8-diesel = "0.3" async-trait = "0.1.92" +aws-lc-rs = "1.18" base64 = "0.23" bb8 = "0.9" chrono = "0.4" diff --git a/README.md b/README.md index 4771fd0e..0bd49d2d 100644 --- a/README.md +++ b/README.md @@ -76,17 +76,23 @@ The following endpoints are injected by the `inject_endpoints` macro: | DELETE | /oauth/client/{client_id}/secret/{secret_id} | Delete an existing secret from an OAuth client | | POST | /oauth/client/{client_id}/redirect_uri | Add a redirect URI to an OAuth cleint | | DELETE | /oauth/client/{client_id}/redirect_uri/{redirect_uri_id} | Delete an existing redirect URI from an OAuth client | +| GET | /oauth/client/{client_id}/service-account/permission | View the permissions an OAuth client holds as a service account | +| POST | /oauth/client/{client_id}/service-account/permission | Grant a single permission to an OAuth client's service account | +| DELETE | /oauth/client/{client_id}/service-account/permission | Remove a single permission from an OAuth client's service account | +| GET | /oauth/client/{client_id}/service-account/token | View the unexpired, unrevoked tokens issued to an OAuth client's service account | +| DELETE | /oauth/client/{client_id}/service-account/token/{token_id} | Revoke a token issued to an OAuth client's service account | +| POST | /oauth/client/{client_id}/service-account/key | Register an Ed25519 public key that an OAuth client's assertions are verified with | +| DELETE | /oauth/client/{client_id}/service-account/key/{key_id} | Remove a public key from an OAuth client | | GET | /login/oauth/{provider}/code/authorize | Start an OAuth authorization_code flow | | GET | /login/oauth/{provider}/code/callback | Internal url for handling return calls from external OAuth providers | | POST | /login/oauth/{provider}/code/token | Complete an authorization_code flow by exchanging an authorization code for an access token | | GET | /login/oauth/{provider}/device | Start an OAuth device_code flow | | POST | /login/oauth/{provider}/device/exchange | Complete a device_code flow by exchanging a request for an access token | +| POST | /oauth/token | Issue an access token to an OAuth client's service account through a client_credentials grant authenticated with a `private_key_jwt` assertion | | GET | /.well-known/openid-configuration | Retrive OpenID configuartion information. Specifically the jwks url | | GET | /.well-known/jwks.json | Retrieve JWKS for verifying access tokens | | GET | /self | View information about the calling user | | GET | /api-user/{identifier} | View information about a specific user | -| POST | /api-user | Create a new user | -| POST | /api-user/{identifier} | Update information on an existing user | | GET | /api-user/{identifier}/token | View all API tokens for an existing user | | POST | /api-user/{identifier}/token | Create a new API token for an existing user | | GET | /api-user/{identifier}/token/{token_identifier} | View an existing API token | @@ -97,7 +103,8 @@ The following endpoints are injected by the `inject_endpoints` macro: | POST | /api-user-provider/{identifier}/link-token | TBD | | GET | /group | View all groups | | POST | /group | Create a new group | -| PUT | /group/{group_id} | Update an existing group | +| POST | /group/{group_id}/permission | Add a single permission to an existing group | +| DELETE | /group/{group_id}/permission | Remove a single permission from an existing group | | DELETE | /group/{group_id} | Delete an existing group | | GET | /mapper | View all mappers | | POST | /mapper | Create a new mapper | diff --git a/remix-auth-vapi/src/types.ts b/remix-auth-vapi/src/types.ts index e5219e3f..017f6215 100644 --- a/remix-auth-vapi/src/types.ts +++ b/remix-auth-vapi/src/types.ts @@ -37,7 +37,7 @@ export type GetUserResponse = { } /** - * Access token claims, per RFC 9068. Note that `scp` is a single + * Access token claims, per RFC 9068 §2.2. Note that `scp` is a single * space-delimited string on the wire, not an array. */ export type VApiAccessTokenClaims = { @@ -45,6 +45,8 @@ export type VApiAccessTokenClaims = { aud: string sub: string prv: string + /** The client the token was issued through. For an OAuth login this is the OAuth client id. */ + client_id?: string | null scp: string exp: number nbf: number diff --git a/v-api-permission-derive/src/lib.rs b/v-api-permission-derive/src/lib.rs index ae614825..ba0453c2 100644 --- a/v-api-permission-derive/src/lib.rs +++ b/v-api-permission-derive/src/lib.rs @@ -663,10 +663,7 @@ fn system_permission_tokens() -> TokenStream { CreateUserApiProviderLinkToken, #[v_api(scope(to = "group:info:w", from = "group:info:w"))] CreateGroup, - #[v_api( - contract(kind = drop, variant = GetGroupsJoined), - scope(to = "group:info:r") - )] + #[v_api(scope(to = "group:info:r"))] GetGroup(newtype_uuid::TypedUuid), #[v_api( expand(kind = iter, variant = GetGroup, source = actor, field = groups) @@ -953,6 +950,8 @@ fn permission_storage_trait_tokens( ) -> proc_macro2::TokenStream { let contract_tokens = permission_storage_contract_tokens(permission_type, contract_settings); let expand_tokens = permission_storage_expand_tokens(permission_type, expand_settings.clone()); + let expand_value_tokens = + permission_storage_expand_value_tokens(permission_type, &expand_settings); let implies_tokens = permission_storage_implies_tokens( permission_type, implies_settings, @@ -964,11 +963,49 @@ fn permission_storage_trait_tokens( impl v_model::permissions::PermissionStorage for #permission_type { #contract_tokens #expand_tokens + #expand_value_tokens #implies_tokens } } } +/// Generates `expand_value`, which splits a permission that carries a set of values into one +/// permission per value. +/// +/// Only iter expansions without an external source qualify. These are permissions who hold all of +/// the direct values required for expansion. Expansions that depend on an external source are left +/// alone. +fn permission_storage_expand_value_tokens( + permission_type: &Ident, + expand_settings: &[(Variant, ExpandSettings)], +) -> proc_macro2::TokenStream { + let branches = expand_settings + .iter() + .filter(|(_, setting)| matches!(setting.kind, ExpandKind::Iter) && setting.source.is_none()) + .map(|(variant, setting)| { + let set_ident = &variant.ident; + let value_ident = &setting.variant; + quote! { + #permission_type::#set_ident(values) => Some( + values + .iter() + .map(|value| #permission_type::#value_ident(value.clone())) + .collect() + ), + } + }) + .collect::>(); + + quote! { + fn expand_value(&self) -> Option> { + match self { + #(#branches)* + _ => None, + } + } + } +} + fn permission_storage_contract_tokens( permission_type: &Ident, contract_settings: Vec<(Variant, ContractSettings)>, @@ -1190,8 +1227,10 @@ fn permission_storage_expand_tokens( quote! { #permission_type::#variant_ident => { - for f0 in &#source.#field { - expanded.push(#permission_type::#target_variant(f0.clone())) + if let Some(#source) = #source { + for f0 in &#source.#field { + expanded.push(#permission_type::#target_variant(f0.clone())) + } } } } @@ -1218,7 +1257,11 @@ fn permission_storage_expand_tokens( ExternalSource::Actor => { let source = source.to_ident(); quote! { - #permission_type::#variant_ident => expanded.push(#permission_type::#target_variant(#source.#field.clone())), + #permission_type::#variant_ident => { + if let Some(#source) = #source { + expanded.push(#permission_type::#target_variant(#source.#field.clone())) + } + } } }, ExternalSource::Extension => { @@ -1251,7 +1294,7 @@ fn permission_storage_expand_tokens( quote! { fn expand( collection: &v_model::Permissions, - actor: &v_model::ApiUser, + actor: Option<&v_model::ApiUser>, actor_permissions: Option<&v_model::Permissions>, extensions: &v_model::ArcMap, ) -> v_model::Permissions { diff --git a/v-api-permission-derive/tests/derive.rs b/v-api-permission-derive/tests/derive.rs index 9fc47cdf..8527be59 100644 --- a/v-api-permission-derive/tests/derive.rs +++ b/v-api-permission-derive/tests/derive.rs @@ -585,112 +585,37 @@ fn test_can_grant_all_empty_targets() { assert!(caller.can_grant_all(&targets)); } -/// Construct an `ApiUser` that holds the dynamic `GetGroupsJoined` permission -/// and is currently a member of `group_id`. -fn joined_actor( - user_id: TypedUuid, - group_id: TypedUuid, -) -> v_model::ApiUser { - use chrono::Utc; - - let mut groups = BTreeSet::new(); - groups.insert(group_id); - - v_model::ApiUser:: { - id: user_id, - permissions: vec![VPermission::GetGroupsJoined].into(), - groups, - created_at: Utc::now(), - updated_at: Utc::now(), - deleted_at: None, - } -} - -/// Exploit for the broken `contract(kind = drop, ...)` handling. -/// -/// `GetGroup(id)` is annotated `contract(kind = drop, variant = GetGroupsJoined)` -/// and is the inverse of `GetGroupsJoined`'s -/// `expand(kind = iter, variant = GetGroup, source = actor, field = groups)`. -/// -/// v-api round-trips permissions through `expand` -> `contract` on every login -/// of an existing user (`register_api_user` -> `add_permissions_to_user` -> -/// `save_api_user`). `contract()` MUST be the exact inverse of `expand()` so -/// that permissions derived from dynamic group membership are never persisted -/// as static grants. -/// -/// Because the `ContractKind::Drop` arm emits no match branch, the concrete -/// `GetGroup(id)` produced by expansion falls through to the catch-all and is -/// stored verbatim. After an admin removes the user from the group, this stale -/// direct grant still authorizes `get_group` (and member enumeration) forever. -/// -/// This assertion currently FAILS, demonstrating the broken revocation. Once -/// the Drop arm discards the concrete variant, it will hold. +/// `contract` keeps a permission over one specific group exactly as it was granted, and keeps the +/// dynamic `GetGroupsJoined` as well. Neither is ever rewritten into the other. Granting +/// visibility of a single group must never widen into visibility of every group the holder has +/// joined, and nothing in the write paths contracts an expanded set, so there is no expansion +/// derived `GetGroup` that would need discarding. #[test] -fn test_contract_drops_dynamic_get_group_grant() { - use std::collections::HashMap; +fn test_contract_keeps_group_permissions_as_written() { use v_model::{AccessGroupId, Permissions}; - let user_id = TypedUuid::::new_v4(); let group_id = TypedUuid::::new_v4(); - let actor = joined_actor(user_id, group_id); - - // The user's stored permissions contain only the dynamic GetGroupsJoined. - let stored: Permissions = vec![VPermission::GetGroupsJoined].into(); - - // On login, stored permissions are expanded against current group membership. - let expanded = VPermission::expand(&stored, &actor, Some(&actor.permissions), &HashMap::new()); - assert!( - expanded - .iter() - .any(|p| matches!(p, VPermission::GetGroup(g) if *g == group_id)), - "precondition: expand() should produce a concrete GetGroup for the joined group, \ - got {:?}", - expanded, - ); + let stored: Permissions = vec![ + VPermission::GetGroup(group_id), + VPermission::GetGroupsJoined, + ] + .into(); - // Before persisting, the expanded set is contracted. The concrete - // GetGroup(group_id) must NOT survive — it is purely derived from dynamic - // group membership and would otherwise become a permanent direct grant. - let contracted = VPermission::contract(&expanded); + let contracted = VPermission::contract(&stored); assert!( - !contracted + contracted .iter() .any(|p| matches!(p, VPermission::GetGroup(g) if *g == group_id)), - "broken revocation: contract() persisted a concrete GetGroup({:?}) derived from group \ - membership. This stale direct grant survives removal from the group, so the user \ - keeps get_group access forever. contracted = {:?}", - group_id, + "a single group grant was not stored as written: {:?}", contracted, ); -} - -/// Companion property: `contract()` must restore the dynamic `GetGroupsJoined` -/// so that the permission survives the login round trip. The current Drop arm -/// neither drops the concrete variant nor re-inserts the target, so -/// `GetGroupsJoined` is silently lost from the persisted set. -/// -/// This assertion currently FAILS. -#[test] -fn test_contract_restores_get_groups_joined() { - use std::collections::HashMap; - use v_model::{AccessGroupId, Permissions}; - - let user_id = TypedUuid::::new_v4(); - let group_id = TypedUuid::::new_v4(); - let actor = joined_actor(user_id, group_id); - - let stored: Permissions = vec![VPermission::GetGroupsJoined].into(); - let expanded = VPermission::expand(&stored, &actor, Some(&actor.permissions), &HashMap::new()); - let contracted = VPermission::contract(&expanded); - assert!( contracted .iter() .any(|p| matches!(p, VPermission::GetGroupsJoined)), - "contract() failed to restore the dynamic GetGroupsJoined permission, so it is lost on \ - the next login and the user's group visibility is no longer tied to membership. \ - contracted = {:?}", + "the dynamic joined groups permission was lost: {:?}", contracted, ); + assert_eq!(2, contracted.iter().count()); } diff --git a/v-api/Cargo.toml b/v-api/Cargo.toml index becdb705..91a80aba 100644 --- a/v-api/Cargo.toml +++ b/v-api/Cargo.toml @@ -55,6 +55,7 @@ yup-oauth2 = { workspace = true } [dev-dependencies] async-trait = { workspace = true } +aws-lc-rs = { workspace = true } mockall = { workspace = true } rsa = { workspace = true, features = ["pem"] } tracing-subscriber = { workspace = true } diff --git a/v-api/src/authn/client_assertion.rs b/v-api/src/authn/client_assertion.rs new file mode 100644 index 00000000..6c90b9ec --- /dev/null +++ b/v-api/src/authn/client_assertion.rs @@ -0,0 +1,574 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Assertions are parsed and checked here rather than through `jsonwebtoken::decode`. The crate +//! types the header `alg` as its own enum, which does not know the RFC 9864 §2.2 `Ed25519` identifier, +//! so an assertion using it would be refused before its signature was ever checked. Once support +//! hsa been added we will consider using the crates implementation. For now only the signature +//! check itself is delegated to the crate. + +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use jsonwebtoken::{Algorithm, DecodingKey, crypto::verify}; +use newtype_uuid::TypedUuid; +use serde::{Deserialize, Deserializer, de::DeserializeOwned, de::Error as _}; +use thiserror::Error; +use v_model::{ + OAuthClientId, + jwk::{OkpPublicKey, PublicJwk}, +}; + +/// The `client_assertion_type` that identifies a JWT assertion (RFC 7523 §2.2) +pub const JWT_BEARER_ASSERTION_TYPE: &str = + "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; + +/// How far the clocks of a client and v-api may disagree, in seconds +pub const CLOCK_SKEW: i64 = 30; + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum AssertionError { + #[error("Assertion is not a compact JWS")] + Malformed, + #[error("Assertion header is not acceptable: {0}")] + Header(String), + #[error("Assertion claims are not acceptable: {0}")] + Claims(String), + #[error("Assertion was signed with a key that is not supported")] + UnsupportedKey, + #[error("Assertion signature is invalid")] + Signature, + #[error("Assertion subject does not match its issuer")] + SubjectMismatch, + #[error("Assertion audience is not this service")] + Audience, + #[error("Assertion has expired")] + Expired, + #[error("Assertion lives longer than is allowed")] + TooLongLived, + #[error("Assertion is not yet valid")] + NotYetValid, + #[error("Assertion was issued in the future")] + IssuedInFuture, + #[error("Assertion has an empty jti")] + MissingJti, +} + +/// The header of an assertion. Unknown parameters are ignored as JWS requires. Parameters that +/// would change which key is trusted or how the assertion is processed are strictly rejected during +/// deserialization. +#[derive(Debug, Deserialize)] +struct AssertionHeader { + alg: AssertionAlgorithm, + kid: String, + + // typ is not required, but if it is specified it must comply to the limited types we support. + #[serde(default, rename = "typ")] + _typ: Option, + + // A key embedded in or referenced by the header is the classic way to make a verifier trust + // a key chosen by an attacker. Assertions are only ever verified against stored keys, so these + // parameters are refused outright. + #[serde(default, rename = "jwk")] + _jwk: Option, + #[serde(default, rename = "jku")] + _jku: Option, + #[serde(default, rename = "x5c")] + _x5c: Option, + #[serde(default, rename = "x5u")] + _x5u: Option, + + // No JWS extensions are supported. + #[serde(default, rename = "crit")] + _crit: Option, +} + +/// RFC 9864 §2.2 registers `Ed25519` as the fully specified identifier and §4.1.2 deprecates the +/// polymorphic `EdDSA`. Both are accepted currently for compatibility. We only support Ed25519 and +/// therefore for our use case they are equivalent. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +enum AssertionAlgorithm { + EdDSA, + Ed25519, +} + +/// RFC 7523 §3 does not require `typ`, so it may be absent. When present it must say the +/// assertion is a JWT, or use the explicit type proposed in draft-ietf-oauth-rfc7523bis. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +enum AssertionType { + #[serde(rename = "JWT")] + Jwt, + #[serde(rename = "client-authentication+jwt")] + ClientAuthentication, +} + +/// Stands in for a header parameter that must never be present +#[derive(Debug)] +struct RefusedParameter; + +impl<'de> Deserialize<'de> for RefusedParameter { + fn deserialize(_deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Err(D::Error::custom( + "header parameters that supply keys or extensions are not accepted", + )) + } +} + +/// The claims of an assertion. The audience must be a single string. RFC 7519 §4.1.3 also allows +/// an array, but we do not support multiple audiences for a single claim and therefore specialize +/// to the string case. +#[derive(Debug, Clone, Deserialize)] +pub struct AssertionClaims { + pub iss: TypedUuid, + pub sub: TypedUuid, + pub aud: String, + pub exp: i64, + pub jti: String, + pub nbf: Option, + pub iat: Option, +} + +/// An assertion whose structure has been checked but whose signature and claims have not. All data +/// carried here is strictly untrusted. +#[derive(Debug)] +pub struct UnverifiedAssertion { + header: AssertionHeader, + claims: AssertionClaims, + signing_input: String, + signature: String, +} + +/// The rules an assertion's claims are checked against. +#[derive(Debug, Clone)] +pub struct AssertionPolicy { + /// Must be the v-api issuer identifier + pub audience: String, + /// The current time as a unix timestamp + pub now: i64, + /// The largest allowed number of seconds between now and the assertion's expiration + pub max_lifetime: i64, +} + +fn decode_segment(segment: &str) -> Result +where + T: DeserializeOwned, +{ + let bytes = URL_SAFE_NO_PAD + .decode(segment) + .map_err(|_| AssertionError::Malformed)?; + serde_json::from_slice(&bytes).map_err(|err| AssertionError::Claims(err.to_string())) +} + +impl UnverifiedAssertion { + /// Splits a compact JWS and checks its header against the header policy + pub fn parse(assertion: &str) -> Result { + let segments = assertion.split('.').collect::>(); + + match segments.as_slice() { + [header, claims, signature] => { + let header_bytes = URL_SAFE_NO_PAD + .decode(header) + .map_err(|_| AssertionError::Malformed)?; + let header = serde_json::from_slice::(&header_bytes) + .map_err(|err| AssertionError::Header(err.to_string()))?; + + Ok(Self { + header, + claims: decode_segment(claims)?, + signing_input: format!( + "{header_segment}.{claims}", + header_segment = segments[0] + ), + signature: signature.to_string(), + }) + } + _ => Err(AssertionError::Malformed), + } + } + + /// The key id the assertion claims to be signed with + pub fn untrusted_kid(&self) -> &str { + &self.header.kid + } + + /// Verifies the signature against a key and then checks the claims against the policy. This + /// MUST be the only way for a caller to extract the claims from the token. + pub fn verify( + self, + key: &PublicJwk, + policy: &AssertionPolicy, + ) -> Result { + let decoding_key = match key { + PublicJwk::Okp(OkpPublicKey::Ed25519 { x, .. }) => { + DecodingKey::from_ed_components(&URL_SAFE_NO_PAD.encode(x)) + .map_err(|_| AssertionError::UnsupportedKey) + } + _ => Err(AssertionError::UnsupportedKey), + }?; + + // Both accepted identifiers name the same Ed25519 signature check + let algorithm = match self.header.alg { + AssertionAlgorithm::EdDSA | AssertionAlgorithm::Ed25519 => Algorithm::EdDSA, + }; + + let valid = verify( + &self.signature, + self.signing_input.as_bytes(), + &decoding_key, + algorithm, + ) + .map_err(|_| AssertionError::Signature)?; + + if !valid { + Err(AssertionError::Signature) + } else { + Self::check_claims(self.claims, policy) + } + } + + fn check_claims( + claims: AssertionClaims, + policy: &AssertionPolicy, + ) -> Result { + let now = policy.now; + + if claims.sub != claims.iss { + Err(AssertionError::SubjectMismatch) + } else if claims.aud != policy.audience { + Err(AssertionError::Audience) + } else if claims.exp.saturating_add(CLOCK_SKEW) <= now { + Err(AssertionError::Expired) + } else if claims.exp.saturating_sub(now) > policy.max_lifetime + CLOCK_SKEW { + Err(AssertionError::TooLongLived) + } else if claims.nbf.is_some_and(|nbf| nbf > now + CLOCK_SKEW) { + Err(AssertionError::NotYetValid) + } else if claims.iat.is_some_and(|iat| iat > now + CLOCK_SKEW) { + Err(AssertionError::IssuedInFuture) + } else if claims.jti.is_empty() { + Err(AssertionError::MissingJti) + } else { + Ok(claims) + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + use aws_lc_rs::{ + rand::SystemRandom, + signature::{Ed25519KeyPair, KeyPair}, + }; + use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; + use chrono::Utc; + use newtype_uuid::TypedUuid; + use serde_json::{Value, json}; + use v_model::{OAuthClientId, jwk::PublicJwk}; + + use super::{AssertionError, AssertionPolicy, CLOCK_SKEW, UnverifiedAssertion}; + + pub const AUDIENCE: &str = "https://test_public_url"; + pub const MAX_LIFETIME: i64 = 300; + + /// A client key pair for signing test assertions with + pub struct TestKey { + pair: Ed25519KeyPair, + } + + impl TestKey { + pub fn new() -> Self { + let pkcs8 = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).unwrap(); + Self { + pair: Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap(), + } + } + + pub fn public_jwk(&self) -> PublicJwk { + PublicJwk::ed25519(self.pair.public_key().as_ref().try_into().unwrap()) + } + + /// Signs an arbitrary header and claims + pub fn sign(&self, header: &Value, claims: &Value) -> String { + let input = format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(header.to_string()), + URL_SAFE_NO_PAD.encode(claims.to_string()) + ); + let signature = self.pair.sign(input.as_bytes()); + format!("{input}.{}", URL_SAFE_NO_PAD.encode(signature.as_ref())) + } + + /// Signs a valid assertion for the client + pub fn assertion(&self, client_id: TypedUuid, kid: &str) -> String { + self.sign(&header(kid), &claims(client_id)) + } + } + + pub fn header(kid: &str) -> Value { + json!({ "alg": "EdDSA", "kid": kid, "typ": "JWT" }) + } + + pub fn claims(client_id: TypedUuid) -> Value { + let now = Utc::now().timestamp(); + json!({ + "iss": client_id, + "sub": client_id, + "aud": AUDIENCE, + "exp": now + 120, + "iat": now, + "jti": TypedUuid::::new_v4().to_string(), + }) + } + + fn policy() -> AssertionPolicy { + AssertionPolicy { + audience: AUDIENCE.to_string(), + now: Utc::now().timestamp(), + max_lifetime: MAX_LIFETIME, + } + } + + fn check(key: &TestKey, assertion: &str) -> Result<(), AssertionError> { + UnverifiedAssertion::parse(assertion)? + .verify(&key.public_jwk(), &policy()) + .map(|_| ()) + } + + fn with(base: Value, member: &str, value: Value) -> Value { + let mut base = base; + base[member] = value; + base + } + + fn without(base: Value, member: &str) -> Value { + let mut base = base; + base.as_object_mut().unwrap().remove(member); + base + } + + #[test] + fn accepts_both_ed25519_identifiers() { + let key = TestKey::new(); + let client = TypedUuid::new_v4(); + + for alg in ["EdDSA", "Ed25519"] { + let assertion = key.sign(&with(header("kid"), "alg", json!(alg)), &claims(client)); + assert_eq!(Ok(()), check(&key, &assertion), "{alg}"); + } + } + + #[test] + fn accepts_the_allowed_types() { + let key = TestKey::new(); + let client = TypedUuid::new_v4(); + + for header in [ + without(header("kid"), "typ"), + with(header("kid"), "typ", json!("client-authentication+jwt")), + ] { + assert_eq!(Ok(()), check(&key, &key.sign(&header, &claims(client)))); + } + + let other = with(header("kid"), "typ", json!("at+jwt")); + assert!(matches!( + check(&key, &key.sign(&other, &claims(client))), + Err(AssertionError::Header(_)) + )); + } + + #[test] + fn exposes_the_kid_before_verification() { + let key = TestKey::new(); + let client = TypedUuid::new_v4(); + let assertion = UnverifiedAssertion::parse(&key.assertion(client, "the-kid")).unwrap(); + + assert_eq!("the-kid", assertion.untrusted_kid()); + } + + /// Every algorithm other than Ed25519 is refused, whatever the signature + #[test] + fn refuses_other_algorithms() { + let key = TestKey::new(); + let client = TypedUuid::new_v4(); + + for alg in ["none", "HS256", "RS256", "PS256", "ES256", "Ed448"] { + let assertion = key.sign(&with(header("kid"), "alg", json!(alg)), &claims(client)); + assert!( + matches!(check(&key, &assertion), Err(AssertionError::Header(_))), + "{alg}" + ); + } + } + + #[test] + fn refuses_a_missing_kid() { + let key = TestKey::new(); + let assertion = key.sign(&without(header("kid"), "kid"), &claims(TypedUuid::new_v4())); + assert!(matches!( + check(&key, &assertion), + Err(AssertionError::Header(_)) + )); + } + + /// Header parameters that supply a key or demand an extension are refused + #[test] + fn refuses_key_and_extension_headers() { + let key = TestKey::new(); + let client = TypedUuid::new_v4(); + + for parameter in ["jwk", "jku", "x5c", "x5u", "crit"] { + let assertion = key.sign( + &with(header("kid"), parameter, json!("value")), + &claims(client), + ); + assert!( + matches!(check(&key, &assertion), Err(AssertionError::Header(_))), + "{parameter}" + ); + } + } + + #[test] + fn refuses_a_signature_from_another_key() { + let key = TestKey::new(); + let assertion = TestKey::new().assertion(TypedUuid::new_v4(), "kid"); + assert_eq!(Err(AssertionError::Signature), check(&key, &assertion)); + } + + #[test] + fn refuses_tampered_claims() { + let key = TestKey::new(); + let assertion = key.assertion(TypedUuid::new_v4(), "kid"); + let segments = assertion.split('.').collect::>(); + let forged = URL_SAFE_NO_PAD.encode(claims(TypedUuid::new_v4()).to_string()); + let tampered = format!("{}.{forged}.{}", segments[0], segments[2]); + + assert_eq!(Err(AssertionError::Signature), check(&key, &tampered)); + } + + #[test] + fn refuses_malformed_assertions() { + let key = TestKey::new(); + for assertion in ["", "a.b", "a.b.c.d", "!!.!!.!!"] { + assert!(check(&key, assertion).is_err(), "{assertion}"); + } + } + + #[test] + fn refuses_a_subject_that_is_not_the_issuer() { + let key = TestKey::new(); + let assertion = key.sign( + &header("kid"), + &with( + claims(TypedUuid::new_v4()), + "sub", + json!(TypedUuid::::new_v4()), + ), + ); + assert_eq!( + Err(AssertionError::SubjectMismatch), + check(&key, &assertion) + ); + } + + /// Only the issuer identifier is an accepted audience. The token endpoint URL and arrays are + /// refused. + #[test] + fn refuses_other_audiences() { + let key = TestKey::new(); + let client = TypedUuid::new_v4(); + + let endpoint = with( + claims(client), + "aud", + json!(format!("{AUDIENCE}/oauth/token")), + ); + assert_eq!( + Err(AssertionError::Audience), + check(&key, &key.sign(&header("kid"), &endpoint)) + ); + + let array = with(claims(client), "aud", json!([AUDIENCE])); + assert!(matches!( + check(&key, &key.sign(&header("kid"), &array)), + Err(AssertionError::Claims(_)) + )); + } + + #[test] + fn refuses_missing_required_claims() { + let key = TestKey::new(); + for claim in ["iss", "sub", "aud", "exp", "jti"] { + let assertion = key.sign(&header("kid"), &without(claims(TypedUuid::new_v4()), claim)); + assert!( + matches!(check(&key, &assertion), Err(AssertionError::Claims(_))), + "{claim}" + ); + } + } + + #[test] + fn refuses_assertions_outside_their_lifetime() { + let key = TestKey::new(); + let client = TypedUuid::new_v4(); + let now = Utc::now().timestamp(); + + for (member, value, expected) in [ + ("exp", now - CLOCK_SKEW - 1, AssertionError::Expired), + ( + "exp", + now + MAX_LIFETIME + CLOCK_SKEW + 60, + AssertionError::TooLongLived, + ), + ("nbf", now + CLOCK_SKEW + 60, AssertionError::NotYetValid), + ("iat", now + CLOCK_SKEW + 60, AssertionError::IssuedInFuture), + ] { + let assertion = key.sign(&header("kid"), &with(claims(client), member, json!(value))); + assert_eq!(Err(expected), check(&key, &assertion), "{member}"); + } + } + + /// Small disagreements between clocks are tolerated + #[test] + fn tolerates_clock_skew() { + let key = TestKey::new(); + let client = TypedUuid::new_v4(); + let now = Utc::now().timestamp(); + + for (member, value) in [ + ("exp", now - CLOCK_SKEW + 5), + ("nbf", now + CLOCK_SKEW - 5), + ("iat", now + CLOCK_SKEW - 5), + ] { + let assertion = key.sign(&header("kid"), &with(claims(client), member, json!(value))); + assert_eq!(Ok(()), check(&key, &assertion), "{member}"); + } + } + + /// An expiration at either end of the representable range is refused without the arithmetic + /// around it overflowing + #[test] + fn refuses_extreme_expirations_without_panicking() { + let key = TestKey::new(); + let client = TypedUuid::new_v4(); + + for (exp, expected) in [ + (i64::MAX, AssertionError::TooLongLived), + (i64::MIN, AssertionError::Expired), + ] { + let assertion = key.sign(&header("kid"), &with(claims(client), "exp", json!(exp))); + assert_eq!(Err(expected), check(&key, &assertion), "{exp}"); + } + } + + #[test] + fn refuses_an_empty_jti() { + let key = TestKey::new(); + let assertion = key.sign( + &header("kid"), + &with(claims(TypedUuid::new_v4()), "jti", json!("")), + ); + assert_eq!(Err(AssertionError::MissingJti), check(&key, &assertion)); + } +} diff --git a/v-api/src/authn/client_key.rs b/v-api/src/authn/client_key.rs new file mode 100644 index 00000000..ae383bd0 --- /dev/null +++ b/v-api/src/authn/client_key.rs @@ -0,0 +1,283 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use schemars::JsonSchema; +use serde::{Deserialize, Deserializer, de::Error as _}; +use sha2::{Digest, Sha256}; +use thiserror::Error; +use v_model::jwk::{OkpPublicKey, PublicJwk}; + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum ClientKeyError { + #[error("Only Ed25519 keys are accepted")] + UnsupportedKey, +} + +/// A public key in JWK form. +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub struct SubmittedJwk { + kty: KeyType, + crv: Curve, + /// The 32 byte Ed25519 public key in unpadded base64url + #[serde(with = "v_model::jwk::base64url_bytes")] + #[schemars(with = "String")] + x: [u8; 32], + #[serde(rename = "use")] + key_use: KeyUse, + /// Optional, as RFC 7517 §4.3 advises against using it alongside `use`. When it is present it + /// must agree with `use`, which for a public signing key means exactly `["verify"]`. + key_ops: Option<[KeyOperation; 1]>, + alg: KeyAlgorithm, + + // These are fields that are strictly rejected. Per RFC 7517 §4 we understand their contents, + // but we are not willing to accept them. A caller sending them implies that they are + // misunderstanding the intent of this key pair. + #[serde(rename = "d")] + #[schemars(skip)] + _private_key: Option, + #[serde(rename = "x5c")] + #[schemars(skip)] + _x5c: Option, + #[serde(rename = "x5u")] + #[schemars(skip)] + _x5u: Option, + #[serde(rename = "x5t")] + #[schemars(skip)] + _x5t: Option, + #[serde(rename = "x5t#S256")] + #[schemars(skip)] + _x5t_s256: Option, +} + +/// The Octet Key Pair key type from RFC 8037 §2 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)] +pub enum KeyType { + #[serde(rename = "OKP")] + Okp, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)] +pub enum Curve { + Ed25519, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)] +pub enum KeyUse { + #[serde(rename = "sig")] + Signature, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)] +pub enum KeyOperation { + #[serde(rename = "verify")] + Verify, +} + +/// The algorithm a key is used with. RFC 9864 §2.2 registers `Ed25519` as the fully specified +/// identifier. We support EdDSA for compatibility. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)] +pub enum KeyAlgorithm { + EdDSA, + Ed25519, +} + +/// Stands in for the `d` member (private key material). It is not allowed. +#[derive(Debug, Clone)] +struct PrivateKeyMember; + +impl<'de> Deserialize<'de> for PrivateKeyMember { + fn deserialize(_deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Err(D::Error::custom( + "private key material must never be submitted", + )) + } +} + +/// Stands in for the certificate members. None of them are allowed. +#[derive(Debug, Clone)] +struct CertificateMember; + +impl<'de> Deserialize<'de> for CertificateMember { + fn deserialize(_deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Err(D::Error::custom("certificate members are not supported")) + } +} + +impl SubmittedJwk { + pub fn into_public_jwk(self) -> PublicJwk { + // These fields have been verified during deserialization, ensuring that the key is of a + // supported form and can be transformed into a PublicJwk + let SubmittedJwk { + kty: KeyType::Okp, + crv: Curve::Ed25519, + x, + key_use: KeyUse::Signature, + key_ops: None | Some([KeyOperation::Verify]), + alg: KeyAlgorithm::EdDSA | KeyAlgorithm::Ed25519, + .. + } = self; + + PublicJwk::ed25519(x) + } +} + +/// The RFC 7638 §3 thumbprint of a public key. +pub trait JwkThumbprint { + fn thumbprint(&self) -> Result; +} + +impl JwkThumbprint for PublicJwk { + fn thumbprint(&self) -> Result { + // RFC 7638 §3 hashes the required members of a key in lexicographic order with no + // whitespace. RFC 8037 §2 defines the required members of an OKP key as crv, kty, and x. + match self { + PublicJwk::Okp(OkpPublicKey::Ed25519 { x, .. }) => { + let canonical = format!( + r#"{{"crv":"Ed25519","kty":"OKP","x":"{}"}}"#, + URL_SAFE_NO_PAD.encode(x) + ); + Ok(URL_SAFE_NO_PAD.encode(Sha256::digest(canonical.as_bytes()))) + } + _ => Err(ClientKeyError::UnsupportedKey), + } + } +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use super::{JwkThumbprint, SubmittedJwk}; + + /// The example Ed25519 public key from RFC 8037 Appendix A.2 + const RFC_8037_X: &str = "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"; + + fn valid() -> Value { + json!({ + "kty": "OKP", + "crv": "Ed25519", + "x": RFC_8037_X, + "use": "sig", + "key_ops": ["verify"], + "alg": "EdDSA", + }) + } + + fn submit(jwk: Value) -> Result { + serde_json::from_value(jwk) + } + + fn with(member: &str, value: Value) -> Value { + let mut jwk = valid(); + jwk[member] = value; + jwk + } + + #[test] + fn accepts_an_ed25519_signing_key() { + assert!(submit(valid()).is_ok()); + assert!(submit(with("alg", json!("Ed25519"))).is_ok()); + } + + /// `key_ops` may be left out, since `use` already says the key verifies signatures + #[test] + fn accepts_a_key_without_key_ops() { + let mut jwk = valid(); + jwk.as_object_mut().unwrap().remove("key_ops"); + + assert_eq!( + submit(valid()).unwrap().into_public_jwk(), + submit(jwk).unwrap().into_public_jwk() + ); + } + + /// Every member the policy describes must be present + #[test] + fn refuses_keys_missing_a_required_member() { + for member in ["kty", "crv", "x", "use", "alg"] { + let mut jwk = valid(); + jwk.as_object_mut().unwrap().remove(member); + assert!(submit(jwk).is_err(), "accepted a key without {member}"); + } + } + + #[test] + fn refuses_values_outside_the_policy() { + for (member, value) in [ + ("kty", json!("EC")), + ("kty", json!("okp")), + ("crv", json!("Ed448")), + ("crv", json!("X25519")), + ("use", json!("enc")), + ("key_ops", json!(["sign"])), + ("key_ops", json!(["verify", "sign"])), + ("key_ops", json!([])), + ("alg", json!("RS256")), + ("alg", json!("ES256")), + ] { + assert!( + submit(with(member, value.clone())).is_err(), + "accepted {member} {value}" + ); + } + } + + /// A client supplied key id and members without rules are ignored rather than refused + #[test] + fn ignores_kid_and_unknown_members() { + let mut jwk = with("kid", json!("chosen-by-client")); + jwk["ext"] = json!(true); + + assert_eq!( + submit(valid()).unwrap().into_public_jwk(), + submit(jwk).unwrap().into_public_jwk() + ); + } + + /// A submitted private key is refused, and the refusal says why + #[test] + fn refuses_private_key_material() { + let err = submit(with("d", json!(RFC_8037_X))).unwrap_err(); + assert!(err.to_string().contains("private key"), "{err}"); + } + + #[test] + fn refuses_certificate_members() { + for member in ["x5c", "x5u", "x5t", "x5t#S256"] { + let err = submit(with(member, json!("value"))).unwrap_err(); + assert!(err.to_string().contains("certificate"), "{member} {err}"); + } + } + + #[test] + fn refuses_public_keys_that_are_not_32_bytes_of_unpadded_base64url() { + for x in [ + json!(format!("{RFC_8037_X}=")), + json!("AAAA"), + json!("not base64!"), + ] { + assert!(submit(with("x", x.clone())).is_err(), "accepted x {x}"); + } + } + + /// The thumbprint RFC 8037 Appendix A.3 gives for its example key + #[test] + fn computes_the_rfc_7638_thumbprint() { + assert_eq!( + "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k", + submit(valid()) + .unwrap() + .into_public_jwk() + .thumbprint() + .unwrap() + ); + } +} diff --git a/v-api/src/authn/jwt.rs b/v-api/src/authn/jwt.rs index 2b466fbb..59fe0e7f 100644 --- a/v-api/src/authn/jwt.rs +++ b/v-api/src/authn/jwt.rs @@ -15,7 +15,8 @@ use serde::{Deserialize, Serialize, de::DeserializeOwned}; use std::{fmt::Debug, sync::Arc}; use thiserror::Error; use tracing::instrument; -use v_model::{AccessTokenId, UserId, UserProviderId}; +use uuid::Uuid; +use v_model::{AccessTokenId, OAuthClientId, ServiceAccountTokenId, UserId, UserProviderId}; use crate::{ApiContext, authn::Signer, context::VContext, permissions::VAppPermission}; @@ -46,12 +47,17 @@ pub struct Jwt { pub claims: T, } +/// The claims of an access token issued to a user. #[derive(Debug, Deserialize, Serialize)] -pub struct Claims { +pub struct UserClaims { pub iss: String, pub aud: String, pub sub: TypedUuid, pub prv: TypedUuid, + // Required by RFC 9068 §2.2. For backwards compatibility this must be optional in this release + // and it can become enforced in the next release. This is either an OAuth client id or a + // Magic Link client id, currently we do not have a way to differentiate during deserialization. + pub client_id: Option, #[serde(with = "scp_format")] pub scp: Vec, pub exp: i64, @@ -59,9 +65,60 @@ pub struct Claims { pub jti: TypedUuid, } +/// The claims of an access token issued to an OAuth client acting as a service account. +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct ServiceAccountClaims { + pub iss: String, + pub aud: String, + pub sub: TypedUuid, + // Required by RFC 9068 §2.2. Because there are no service account tokens prior to v0.6.0 it is + // safe the make this required as all issued tokens will have it. + pub client_id: TypedUuid, + #[serde(with = "scp_format")] + pub scp: Vec, + pub exp: i64, + pub nbf: i64, + pub jti: TypedUuid, +} + +impl ServiceAccountClaims { + pub fn new( + ctx: &VContext, + id: Option>, + client_id: &TypedUuid, + scope: Vec, + expires_at: DateTime, + ) -> Self + where + T: VAppPermission, + { + ServiceAccountClaims { + iss: ctx.issuer(), + aud: ctx.public_url().to_string(), + sub: *client_id, + client_id: *client_id, + scp: scope, + exp: expires_at.timestamp(), + nbf: Utc::now().timestamp(), + jti: id.unwrap_or_else(TypedUuid::new_v4), + } + } +} + +/// User and service account tokens do not overlap in their structure, and this is critical to +/// correctness. Both carry `client_id`, but a user token always carries `prv`, which a service +/// account token refuses as an unknown claim. +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum TokenClaims { + ServiceAccount(ServiceAccountClaims), + User(UserClaims), +} + /// Serialize and deserialize the `scp` claim as a space-delimited string per /// RFC 9068 §2.2.2 / RFC 6749 §3.3. Internally the claim is stored as a -/// `Vec` for convenient iteration, but on the wire it is always a +/// `Vec` for convenience, but on the wire it is always a /// single space-separated string (empty string when there are no scopes). mod scp_format { use serde::{self, Deserialize, Deserializer, Serializer}; @@ -89,23 +146,25 @@ mod scp_format { } } -impl Claims { +impl UserClaims { pub fn new( ctx: &VContext, id: Option>, user: &TypedUuid, provider: &TypedUuid, + client_id: Uuid, scope: Vec, expires_at: DateTime, ) -> Self where T: VAppPermission, { - Claims { + UserClaims { iss: ctx.issuer(), aud: ctx.public_url().to_string(), sub: *user, prv: *provider, + client_id: Some(client_id), scp: scope, exp: expires_at.timestamp(), nbf: Utc::now().timestamp(), @@ -266,12 +325,13 @@ mod tests { /// Build a minimal `Claims` value for serialization tests. The non-scp /// fields are placeholders — only the `scp` field matters here. - fn test_claims(scp: Vec) -> Claims { - Claims { + fn test_claims(client_id: Uuid, scp: Vec) -> UserClaims { + UserClaims { iss: "test".into(), aud: "test".into(), sub: TypedUuid::new_v4(), prv: TypedUuid::new_v4(), + client_id: Some(client_id), scp, exp: 0, nbf: 0, @@ -281,7 +341,10 @@ mod tests { #[test] fn scp_serializes_as_space_delimited_string() { - let claims = test_claims(vec!["user:info:r".into(), "group:info:w".into()]); + let claims = test_claims( + Uuid::new_v4(), + vec!["user:info:r".into(), "group:info:w".into()], + ); let json: Value = serde_json::to_value(&claims).unwrap(); assert_eq!( json["scp"], @@ -292,7 +355,7 @@ mod tests { #[test] fn scp_single_scope_serializes_as_string() { - let claims = test_claims(vec!["full".into()]); + let claims = test_claims(Uuid::new_v4(), vec!["full".into()]); let json: Value = serde_json::to_value(&claims).unwrap(); assert_eq!( json["scp"], @@ -303,7 +366,7 @@ mod tests { #[test] fn scp_empty_vec_serializes_as_empty_string() { - let claims = test_claims(vec![]); + let claims = test_claims(Uuid::new_v4(), vec![]); let json: Value = serde_json::to_value(&claims).unwrap(); assert_eq!( json["scp"], @@ -336,9 +399,20 @@ mod tests { #[test] fn scp_round_trips_through_json() { - let original = test_claims(vec!["user:info:r".into(), "full".into()]); + let original = test_claims(Uuid::new_v4(), vec!["user:info:r".into(), "full".into()]); let json_str = serde_json::to_string(&original).unwrap(); - let decoded: Claims = serde_json::from_str(&json_str).unwrap(); + let decoded: UserClaims = serde_json::from_str(&json_str).unwrap(); assert_eq!(decoded.scp, original.scp); } + + /// The client a user token was issued through is named on the wire, as RFC 9068 §2.2 asks + #[test] + fn user_claims_name_their_client() { + let client_id = Uuid::new_v4(); + let value = serde_json::to_value(test_claims(client_id, vec![])).unwrap(); + assert_eq!(Value::String(client_id.to_string()), value["client_id"]); + + let claims: UserClaims = serde_json::from_value(value).unwrap(); + assert_eq!(Some(client_id), claims.client_id); + } } diff --git a/v-api/src/authn/mod.rs b/v-api/src/authn/mod.rs index ec490e82..06840f1b 100644 --- a/v-api/src/authn/mod.rs +++ b/v-api/src/authn/mod.rs @@ -24,7 +24,10 @@ use v_api_param::ParamResolutionError; use v_model::permissions::PermissionStorage; use crate::{ - authn::{jwt::Claims, key::RawKey}, + authn::{ + jwt::{ServiceAccountClaims, TokenClaims, UserClaims}, + key::RawKey, + }, context::ApiContext, permissions::VAppPermission, util::response::unauthorized, @@ -32,6 +35,8 @@ use crate::{ use self::jwt::Jwt; +pub mod client_assertion; +pub mod client_key; pub mod jwt; pub mod key; @@ -45,15 +50,35 @@ pub enum AuthError { // A token that provides authentication and optionally (JWT) authorization claims pub enum AuthToken { + ServiceAccount(Jwt), + User(UserToken), +} + +pub enum UserToken { ApiKey(RawKey), - Jwt(Jwt), + Session(Jwt), } impl Debug for AuthToken { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::ApiKey(_) => f.debug_struct("AuthToken").finish(), - Self::Jwt(jwt) => f.debug_struct("AuthToken").field("jwt", jwt).finish(), + Self::User(UserToken::ApiKey(_)) => f.debug_struct("AuthToken").finish(), + Self::User(UserToken::Session(jwt)) => { + f.debug_struct("AuthToken").field("jwt", jwt).finish() + } + Self::ServiceAccount(jwt) => f + .debug_struct("AuthToken") + .field("service_account", jwt) + .finish(), + } + } +} + +impl From> for AuthToken { + fn from(jwt: Jwt) -> Self { + match jwt.claims { + TokenClaims::User(claims) => AuthToken::User(UserToken::Session(Jwt { claims })), + TokenClaims::ServiceAccount(claims) => AuthToken::ServiceAccount(Jwt { claims }), } } } @@ -82,12 +107,12 @@ impl AuthToken { // Attempt to decode an API key from the token. If that fails then attempt to verify the // token as a JWT - let jwt = Jwt::new(ctx.v_ctx(), &token).await; + let jwt = Jwt::::new(ctx.v_ctx(), &token).await; match jwt { Ok(token) => { tracing::trace!("Extracted auth token"); - Ok(AuthToken::Jwt(token)) + Ok(token.into()) } Err(err) => { tracing::debug!( @@ -96,12 +121,12 @@ impl AuthToken { "Token is not a JWT, falling back to API key" ); - Ok(AuthToken::ApiKey( + Ok(AuthToken::User(UserToken::ApiKey( RawKey::try_from(token.as_str()).map_err(|err| { tracing::info!(?err, "Failed to parse API key"); AuthError::FailedToExtract })?, - )) + ))) } } } diff --git a/v-api/src/config.rs b/v-api/src/config.rs index 772df501..195661dc 100644 --- a/v-api/src/config.rs +++ b/v-api/src/config.rs @@ -18,7 +18,7 @@ use rsa::{ }; use secrecy::{ExposeSecret, SecretString}; use serde::{ - Deserialize, Deserializer, + Deserialize, Deserializer, Serialize, de::{self, Visitor}, }; use std::path::{Path, PathBuf}; @@ -450,3 +450,23 @@ impl ResolvedAsymmetricKey { } } } + +/// Limits that apply to the client credentials grant +#[derive(Debug, Clone, Copy, Deserialize, Serialize)] +pub struct ClientCredentialsConfig { + /// How long an access token issued to a service account remains valid, in seconds + pub token_expiration: i64, + /// The largest allowed number of seconds between now and the expiration of a client + /// assertion. This keeps assertions from being used as long lived credentials, and bounds how + /// long their jti must be remembered. + pub max_assertion_lifetime: i64, +} + +impl Default for ClientCredentialsConfig { + fn default() -> Self { + Self { + token_expiration: 3600, + max_assertion_lifetime: 300, + } + } +} diff --git a/v-api/src/context/auth.rs b/v-api/src/context/auth.rs index 676e21cf..7dcf0a45 100644 --- a/v-api/src/context/auth.rs +++ b/v-api/src/context/auth.rs @@ -7,7 +7,7 @@ use dropshot::RequestContext; use jsonwebtoken::jwk::JwkSet; use serde::Serialize; use std::{collections::HashMap, fmt::Debug, sync::Arc}; -use v_model::permissions::Caller; +use v_model::permissions::{Caller, Principal}; use crate::{ ApiContext, @@ -65,12 +65,12 @@ where ]); Ok(Self { unauthenticated_caller: Caller { - id: "00000000-0000-4000-8000-000000000000".parse().unwrap(), + principal: Principal::User("00000000-0000-4000-8000-000000000000".parse().unwrap()), permissions: vec![].into(), extensions: HashMap::default(), }, registration_caller: Caller { - id: "00000000-0000-4000-8000-000000000001".parse().unwrap(), + principal: Principal::User("00000000-0000-4000-8000-000000000001".parse().unwrap()), permissions: registration_caller_additional_permissions.into(), extensions: HashMap::default(), }, diff --git a/v-api/src/context/group.rs b/v-api/src/context/group.rs index 1b27a559..08cb04d4 100644 --- a/v-api/src/context/group.rs +++ b/v-api/src/context/group.rs @@ -6,7 +6,7 @@ use newtype_uuid::TypedUuid; use std::sync::Arc; use v_model::{ AccessGroup, AccessGroupId, NewAccessGroup, - permissions::Caller, + permissions::{Caller, PermissionStorage, Permissions}, storage::{AccessGroupFilter, AccessGroupStore, ListPagination, StoreError}, }; @@ -16,6 +16,13 @@ use crate::{ response::{OptionalResource, ResourceResult, resource_conflict, resource_restricted}, }; +/// A change to a stored group. Each kind of change carries what is needed to check the caller's +/// authority to make it. +enum GroupChange<'a, T> { + AddPermission(T), + RemovePermission(&'a T), +} + #[derive(Clone)] pub struct GroupContext { storage: Arc>, @@ -126,24 +133,94 @@ where } } - pub async fn update_group( + /// Adds a permission to a group. + pub async fn add_permission_to_group( &self, caller: &Caller, - group: NewAccessGroup, + group_id: &TypedUuid, + permission: T, ) -> ResourceResult, StoreError> { - if self.is_preset(&group.id) { - return resource_conflict(); - } + self.modify_group(caller, group_id, GroupChange::AddPermission(permission)) + .await + } - if caller.can(&VPermission::ManageGroup(group.id).into()) - && caller.can_grant_all(&group.permissions) - { - Ok(AccessGroupStore::upsert(&*self.storage, &group).await?) + /// Removes a permission from a group. + pub async fn remove_permission_from_group( + &self, + caller: &Caller, + group_id: &TypedUuid, + permission: &T, + ) -> ResourceResult, StoreError> { + self.modify_group(caller, group_id, GroupChange::RemovePermission(permission)) + .await + } + + /// Applies a change to a stored group. + async fn modify_group( + &self, + caller: &Caller, + group_id: &TypedUuid, + change: GroupChange<'_, T>, + ) -> ResourceResult, StoreError> { + if self.is_preset(group_id) { + resource_conflict() + } else if Self::can_make_change(caller, group_id, &change) { + let current = self.get_group(caller, group_id).await?; + + let mut update = NewAccessGroup { + id: current.id, + name: current.name, + permissions: current.permissions.expand_values(), + }; + Self::apply_change(&mut update, change); + update.permissions = ::contract(&update.permissions); + + match AccessGroupStore::update(&*self.storage, &update, current.generation).await? { + Some(updated) => Ok(updated), + None => { + tracing::info!( + ?group_id, + generation = current.generation, + "Group was written by someone else since it was read" + ); + resource_conflict() + } + } } else { resource_restricted() } } + /// Returns true if the caller has the authority to make the change to the group + fn can_make_change( + caller: &Caller, + group_id: &TypedUuid, + change: &GroupChange, + ) -> bool { + let permission = match change { + GroupChange::AddPermission(permission) => permission, + GroupChange::RemovePermission(permission) => *permission, + }; + + caller.can(&VPermission::ManageGroup(*group_id).into()) && caller.can_grant(permission) + } + + fn apply_change(update: &mut NewAccessGroup, change: GroupChange) { + match change { + GroupChange::AddPermission(permission) => { + for value in Permissions::from_iter([permission]) + .expand_values() + .into_iter() + { + update.permissions.insert(value); + } + } + GroupChange::RemovePermission(permission) => { + update.permissions = update.permissions.without(permission); + } + } + } + pub async fn delete_group( &self, caller: &Caller, @@ -167,11 +244,14 @@ where mod tests { use chrono::Utc; use newtype_uuid::{GenericUuid, TypedUuid}; - use std::{collections::BTreeSet, sync::Arc}; + use std::{ + collections::BTreeSet, + sync::{Arc, Mutex}, + }; use uuid::Uuid; use v_model::{ AccessGroup, AccessGroupSource, NewAccessGroup, - permissions::{Caller, Permissions}, + permissions::{Caller, Permissions, Principal}, storage::{AccessGroupFilter, MockAccessGroupStore}, }; @@ -190,6 +270,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, } } @@ -202,6 +283,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, } } @@ -223,7 +305,7 @@ mod tests { fn admin_caller() -> Caller { Caller { - id: TypedUuid::new_v4(), + principal: Principal::User(TypedUuid::new_v4()), permissions: vec![ VPermission::GetGroupsAll, VPermission::CreateGroup, @@ -290,17 +372,15 @@ mod tests { let ctx = ctx_with_preset(vec![]); let preset = preset_group("admins"); - let update = ctx - .update_group( - &admin_caller(), - NewAccessGroup { - id: preset.id, - name: "renamed".to_string(), - permissions: Permissions::new(), - }, - ) + let add = ctx + .add_permission_to_group(&admin_caller(), &preset.id, VPermission::CreateGroup) + .await; + assert!(matches!(add, Err(ResourceError::Conflict))); + + let remove = ctx + .remove_permission_from_group(&admin_caller(), &preset.id, &VPermission::CreateGroup) .await; - assert!(matches!(update, Err(ResourceError::Conflict))); + assert!(matches!(remove, Err(ResourceError::Conflict))); let delete = ctx.delete_group(&admin_caller(), &preset.id).await; assert!(matches!(delete, Err(ResourceError::Conflict))); @@ -324,4 +404,136 @@ mod tests { assert!(matches!(create, Err(ResourceError::Conflict))); } + + /// The permissions written by each successful group change + type GroupWrites = Arc>>>; + + /// A context holding one stored group with the supplied permissions. Every write succeeds + /// and the written permissions are recorded. + fn ctx_with_group( + permissions: Permissions, + ) -> ( + GroupContext, + AccessGroup, + GroupWrites, + ) { + let group = AccessGroup { + permissions, + ..dynamic_group("engineering") + }; + let writes: GroupWrites = Arc::new(Mutex::new(vec![])); + + let mut group_store = MockAccessGroupStore::new(); + let stored = group.clone(); + group_store + .expect_get() + .returning(move |_, _| Ok(Some(stored.clone()))); + let recorder = writes.clone(); + let template = group.clone(); + group_store.expect_update().returning(move |update, _| { + recorder.lock().unwrap().push(update.permissions.clone()); + Ok(Some(AccessGroup { + name: update.name.clone(), + permissions: update.permissions.clone(), + ..template.clone() + })) + }); + + let mut storage = MockStorage::new(); + storage.access_group_store = Some(Arc::new(group_store)); + + (GroupContext::new(Arc::new(storage)), group, writes) + } + + fn caller_with(permissions: Vec) -> Caller { + Caller { + principal: Principal::User(TypedUuid::new_v4()), + permissions: permissions.into(), + extensions: Default::default(), + } + } + + /// Every member receives a group's permissions, so adding one requires managing the group + /// and being able to grant the permission + #[tokio::test] + async fn adding_a_group_permission_requires_grant() { + let (ctx, group, writes) = ctx_with_group(Permissions::new()); + + let cannot_grant = caller_with(vec![VPermission::ManageGroup(group.id)]); + let refused = ctx + .add_permission_to_group(&cannot_grant, &group.id, VPermission::CreateMapper) + .await; + assert!(matches!(refused, Err(ResourceError::Restricted))); + assert!(writes.lock().unwrap().is_empty()); + + let can_grant = caller_with(vec![ + VPermission::GetGroup(group.id), + VPermission::ManageGroup(group.id), + VPermission::CreateMapper, + ]); + let updated = ctx + .add_permission_to_group(&can_grant, &group.id, VPermission::CreateMapper) + .await + .unwrap(); + assert!(updated.permissions.can(&VPermission::CreateMapper)); + } + + /// Removing a group permission requires being able to grant it, so the group's members never + /// lose permissions outside of the caller's authority + #[tokio::test] + async fn removing_a_group_permission_requires_grant() { + let (ctx, group, writes) = + ctx_with_group(vec![VPermission::CreateMapper, VPermission::CreateGroup].into()); + + let cannot_grant = caller_with(vec![VPermission::ManageGroup(group.id)]); + let refused = ctx + .remove_permission_from_group(&cannot_grant, &group.id, &VPermission::CreateMapper) + .await; + assert!(matches!(refused, Err(ResourceError::Restricted))); + assert!(writes.lock().unwrap().is_empty()); + + let can_grant = caller_with(vec![ + VPermission::GetGroup(group.id), + VPermission::ManageGroup(group.id), + VPermission::CreateMapper, + ]); + let updated = ctx + .remove_permission_from_group(&can_grant, &group.id, &VPermission::CreateMapper) + .await + .unwrap(); + assert!(!updated.permissions.can(&VPermission::CreateMapper)); + assert!(updated.permissions.can(&VPermission::CreateGroup)); + } + + /// A write against a generation that has moved on is refused as a conflict after a single + /// attempt, and is never retried + #[tokio::test] + async fn a_stale_group_write_is_a_conflict() { + let group = dynamic_group("engineering"); + let stored = group.clone(); + + let mut group_store = MockAccessGroupStore::new(); + group_store + .expect_get() + .times(1) + .returning(move |_, _| Ok(Some(stored.clone()))); + group_store + .expect_update() + .times(1) + .returning(|_, _| Ok(None)); + + let mut storage = MockStorage::new(); + storage.access_group_store = Some(Arc::new(group_store)); + let ctx = GroupContext::new(Arc::new(storage)); + + let manager = caller_with(vec![ + VPermission::GetGroup(group.id), + VPermission::ManageGroup(group.id), + VPermission::CreateMapper, + ]); + let conflict = ctx + .add_permission_to_group(&manager, &group.id, VPermission::CreateMapper) + .await; + assert!(matches!(conflict, Err(ResourceError::Conflict))); + } } diff --git a/v-api/src/context/magic_link.rs b/v-api/src/context/magic_link.rs index e5e96b2d..73ad5bc9 100644 --- a/v-api/src/context/magic_link.rs +++ b/v-api/src/context/magic_link.rs @@ -448,7 +448,7 @@ mod tests { use uuid::Uuid; use v_model::{ MagicLink, MagicLinkAttempt, MagicLinkId, MagicLinkRedirectUri, MagicLinkSecret, - permissions::Caller, + permissions::{Caller, Principal}, schema_ext::{MagicLinkAttemptState, MagicLinkMedium}, storage::{ MockMagicLinkAttemptStore, MockMagicLinkRedirectUriStore, MockMagicLinkSecretStore, @@ -764,7 +764,7 @@ mod tests { fn caller_for_client(client_id: TypedUuid) -> Caller { Caller { - id: TypedUuid::new_v4(), + principal: Principal::User(TypedUuid::new_v4()), permissions: vec![ VPermission::GetMagicLinkClient(client_id), VPermission::ManageMagicLinkClient(client_id), diff --git a/v-api/src/context/mapping.rs b/v-api/src/context/mapping.rs index c8141ace..7cd7c9d6 100644 --- a/v-api/src/context/mapping.rs +++ b/v-api/src/context/mapping.rs @@ -6,8 +6,8 @@ use newtype_uuid::TypedUuid; use serde_json::Value; use std::{collections::BTreeSet, sync::Arc}; use v_model::{ - AccessGroupId, Mapper, MapperEvent, MapperId, MapperSource, NewMapper, NewMapperEvent, - Permissions, UserId, + AccessGroup, AccessGroupId, Mapper, MapperEvent, MapperId, MapperSource, NewMapper, + NewMapperEvent, UserId, permissions::Caller, storage::{ListPagination, MapperEventStore, MapperFilter, MapperStore, StoreError}, }; @@ -15,13 +15,21 @@ use v_model::{ use crate::{ VApiStorage, endpoints::login::UserInfo, - mapper::MappingEngine, + mapper::{MappingEngine, resolve_mapped_groups}, permissions::{VAppPermission, VPermission}, - response::{OptionalResource, ResourceResult, resource_restricted}, + response::{OptionalResource, ResourceError, ResourceResult, resource_restricted}, }; +#[derive(Debug, thiserror::Error)] +pub enum AddMapperError { + #[error("Mapper rule is invalid")] + InvalidRule, + #[error(transparent)] + Resource(#[from] ResourceError), +} + pub struct MappingContext { - engine: Option>>, + engine: Option>, storage: Arc>, preset_mappers: Vec, } @@ -44,8 +52,8 @@ where pub fn set_engine( &mut self, - engine: Option>>, - ) -> Option>> { + engine: Option>, + ) -> Option> { let previous = self.engine.take(); self.engine = engine; previous @@ -63,7 +71,7 @@ where match &self.engine { Some(engine) => { tracing::trace!(?value, "Validating mapping rule"); - engine.validate_mapping_data(value) + engine.validate_mapping_data(value) && engine.is_accepted(value) } None => { tracing::warn!("No mapping rule is installed to validate rules"); @@ -92,15 +100,75 @@ where } } + /// Stores a new mapper. pub async fn add_mapper( &self, caller: &Caller, + visible_groups: &[AccessGroup], new_mapper: &NewMapper, - ) -> ResourceResult { - if caller.can(&VPermission::CreateMapper.into()) { - Ok(MapperStore::upsert(&*self.storage, new_mapper).await?) + ) -> Result { + if !caller.can(&VPermission::CreateMapper.into()) { + Err(ResourceError::Restricted.into()) + } else if !self.validate(&new_mapper.rule) { + Err(AddMapperError::InvalidRule) + } else if !self.can_grant_mapping(caller, visible_groups, &new_mapper.rule) { + Err(ResourceError::Restricted.into()) } else { - resource_restricted() + let mapper = MapperStore::upsert(&*self.storage, new_mapper) + .await + .map_err(ResourceError::from)?; + Ok(mapper) + } + } + + // TODO: Really don't like that we are passing in the visible_groups here. Needs some more + // thought before figuring out how this is changed. + + /// Returns true if the caller could grant everything the rule grants. + fn can_grant_mapping( + &self, + caller: &Caller, + visible_groups: &[AccessGroup], + rule: &Value, + ) -> bool { + match self + .engine + .as_ref() + .map(|engine| engine.create_mapping(rule)) + { + Some(Ok(mapping)) => { + let grants = mapping.grants(); + let named = grants + .groups + .iter() + .map(|name| visible_groups.iter().find(|group| &group.name == name)) + .collect::>>(); + + match named { + Some(named) => named.iter().all(|group| { + caller.can(&VPermission::ManageGroupMembership(group.id).into()) + && caller.can_grant_all(&group.permissions) + }), + None => { + tracing::warn!( + groups = ?grants.groups, + "Mapping rule names a group that does not exist or is not visible" + ); + false + } + } + } + Some(Err(err)) => { + tracing::warn!( + ?err, + "Failed to build a mapping rule to check what it grants" + ); + false + } + None => { + tracing::warn!("No mapping engine is installed to determine what a rule grants"); + false + } } } @@ -116,13 +184,14 @@ where } } + /// The permissions and groups that every matching mapper hands to the user. pub async fn get_mapped_fields( &self, caller: &Caller, + visible_groups: &[AccessGroup], info: &UserInfo, user_id: TypedUuid, - ) -> ResourceResult<(Permissions, BTreeSet>), StoreError> { - let mut mapped_permissions = Permissions::new(); + ) -> ResourceResult>, StoreError> { let mut mapped_groups = BTreeSet::new(); // We only need to run mapping logic if there is mapping engine available to transform @@ -136,24 +205,26 @@ where tracing::trace!(?mapper.name, is_preset, "Attempt to run mapper"); // Try to transform this mapper into a mapping - let mapping = engine.create_mapping(mapper.clone()); + let mapping = engine.create_mapping(&mapper.rule); - let (mut permissions, mut groups) = match mapping { + let mut groups = match mapping { Ok(mapping) => { - tracing::trace!(?mapper.name, "Applying mapping"); - ( - mapping.permissions_for(info).await?, - mapping.groups_for(info).await?, - ) + if mapping.matches(info).await { + tracing::trace!(?mapper.name, "Applying mapping"); + let grants = mapping.grants(); + resolve_mapped_groups(&grants.groups, visible_groups) + } else { + BTreeSet::default() + } } Err(err) => { // Errors here can be expected. They are reported, but not acted upon tracing::info!(?err, "No mapping was found for mapper"); - (Permissions::new(), BTreeSet::default()) + BTreeSet::default() } }; - let apply = if !permissions.is_empty() || !groups.is_empty() { + let apply = if !groups.is_empty() { if is_preset { // Preset mappers always apply - no activation gating true @@ -190,13 +261,12 @@ where ); } - mapped_permissions.append(&mut permissions); mapped_groups.append(&mut groups); } } }; - Ok((mapped_permissions, mapped_groups)) + Ok(mapped_groups) } // TODO: Create a permission for this that only the registration user has @@ -231,3 +301,256 @@ where MapperEventStore::record(&*self.storage, &event).await } } + +#[cfg(test)] +mod tests { + use chrono::Utc; + use newtype_uuid::TypedUuid; + use serde_json::json; + use std::{collections::BTreeSet, sync::Arc}; + use v_model::{ + AccessGroup, AccessGroupSource, Mapper, MapperEvent, MapperSource, NewMapper, + permissions::{Caller, Permissions}, + storage::{MockMapperEventStore, MockMapperStore}, + }; + + use super::{AddMapperError, MappingContext}; + use crate::{ + context::test_mocks::MockStorage, + endpoints::login::{ExternalUserId, UserInfo}, + mapper::DefaultMappingEngine, + permissions::VPermission, + response::ResourceError, + }; + + fn group(name: &str) -> AccessGroup { + AccessGroup { + id: TypedUuid::new_v4(), + name: name.to_string(), + permissions: vec![VPermission::CreateGroup].into(), + source: AccessGroupSource::Dynamic, + created_at: Utc::now(), + updated_at: Utc::now(), + deleted_at: None, + generation: 0, + } + } + + /// A mapping context using the default engine, whose store accepts new mappers + fn mapping_context() -> MappingContext { + let mut mapper_store = MockMapperStore::new(); + mapper_store.expect_upsert().returning(|mapper| { + Ok(Mapper { + id: mapper.id, + name: mapper.name.clone(), + rule: mapper.rule.clone(), + activations: mapper.activations, + max_activations: mapper.max_activations, + source: MapperSource::Dynamic, + depleted_at: None, + created_at: Utc::now(), + updated_at: Utc::now(), + deleted_at: None, + }) + }); + + let mut storage = MockStorage::new(); + storage.mapper_store = Some(Arc::new(mapper_store)); + + let mut mapping = MappingContext::new(Arc::new(storage)); + mapping.set_engine(Some(Arc::new(DefaultMappingEngine))); + mapping + } + + fn mapper(groups: Vec<&str>) -> NewMapper { + NewMapper { + id: TypedUuid::new_v4(), + name: "rule".to_string(), + rule: json!({ "rule": "default", "groups": groups }), + activations: None, + max_activations: None, + } + } + + fn caller_with(permissions: Vec) -> Caller { + Caller::from(Permissions::::from(permissions)) + } + + /// Mapping a user into a group is the same as adding them to it, so the creator needs the + /// group's membership permission and must be able to grant the group's permissions + #[tokio::test] + async fn creating_a_mapper_requires_adding_to_its_groups() { + let engineering = group("engineering"); + let visible = vec![engineering.clone()]; + let mapping = mapping_context(); + let rule = mapper(vec!["engineering"]); + + let no_membership = caller_with(vec![VPermission::CreateMapper, VPermission::CreateGroup]); + let refused = mapping.add_mapper(&no_membership, &visible, &rule).await; + assert!(matches!( + refused, + Err(AddMapperError::Resource(ResourceError::Restricted)) + )); + + let cannot_grant_group = caller_with(vec![ + VPermission::CreateMapper, + VPermission::ManageGroupMembership(engineering.id), + ]); + let refused = mapping + .add_mapper(&cannot_grant_group, &visible, &rule) + .await; + assert!(matches!( + refused, + Err(AddMapperError::Resource(ResourceError::Restricted)) + )); + + let can_add = caller_with(vec![ + VPermission::CreateMapper, + VPermission::ManageGroupMembership(engineering.id), + VPermission::CreateGroup, + ]); + assert!(mapping.add_mapper(&can_add, &visible, &rule).await.is_ok()); + } + + /// Every group a rule names must be one the caller can see. A name that resolves to nothing + /// could later resolve to a group someone else creates, and a group the caller can not see + /// is not theirs to hand out, so both are refused. + #[tokio::test] + async fn creating_a_mapper_refuses_groups_the_caller_can_not_see() { + let mapping = mapping_context(); + let visible = vec![group("engineering")]; + let rule = mapper(vec!["engineering", "not-visible"]); + + let caller = caller_with(vec![ + VPermission::CreateMapper, + VPermission::ManageGroupMembershipsAll, + VPermission::CreateGroup, + ]); + let refused = mapping.add_mapper(&caller, &visible, &rule).await; + assert!(matches!( + refused, + Err(AddMapperError::Resource(ResourceError::Restricted)) + )); + } + + fn preset_mapper(name: &str, rule: serde_json::Value) -> Mapper { + Mapper { + id: TypedUuid::new_v4(), + name: name.to_string(), + rule, + activations: None, + max_activations: None, + source: MapperSource::Preset, + depleted_at: None, + created_at: Utc::now(), + updated_at: Utc::now(), + deleted_at: None, + } + } + + /// A login applies exactly the groups of each rule it matches, resolved against the groups + /// the caller can see. A rule that does not match contributes nothing. + #[tokio::test] + async fn logins_apply_exactly_the_grants_of_matching_rules() { + let engineering = group("engineering"); + let admins = group("admins"); + let visible = vec![engineering.clone(), admins]; + + let mut mapper_store = MockMapperStore::new(); + mapper_store.expect_list().returning(|_, _| Ok(vec![])); + let mut event_store = MockMapperEventStore::new(); + event_store.expect_record().returning(|event| { + Ok(MapperEvent { + id: event.id, + mapper_id: event.mapper_id, + mapper_name: event.mapper_name.clone(), + user_id: event.user_id, + rule: event.rule.clone(), + source: event.source, + created_at: Utc::now(), + }) + }); + + let mut storage = MockStorage::new(); + storage.mapper_store = Some(Arc::new(mapper_store)); + storage.mapper_event_store = Some(Arc::new(event_store)); + + let mut mapping = MappingContext::new(Arc::new(storage)); + mapping.set_engine(Some(Arc::new(DefaultMappingEngine))); + mapping.set_preset_mappers(vec![ + preset_mapper( + "matching", + json!({ "rule": "default", "groups": ["engineering"] }), + ), + preset_mapper( + "not-matching", + json!({ + "rule": "email_address", + "email": "someone-else@example.com", + "groups": ["admins"], + }), + ), + ]); + + let registration = caller_with(vec![VPermission::GetMappersAll]); + let user = UserInfo { + external_id: ExternalUserId::MagicLink("user@example.com".to_string()), + verified_emails: vec!["user@example.com".to_string()], + display_name: None, + idp_token: None, + }; + + let groups = mapping + .get_mapped_fields(®istration, &visible, &user, TypedUuid::new_v4()) + .await + .unwrap(); + + assert_eq!(BTreeSet::from([engineering.id]), groups); + } + + /// New mappers must use the current shape, even when the caller could grant everything the + /// original shape asks for. The caller is shown to be allowed to create the same rule in the + /// current shape, so the refusals can only come from the shape of the rule. + #[tokio::test] + async fn creating_a_mapper_refuses_the_original_shape() { + let engineering = group("engineering"); + let visible = vec![engineering.clone()]; + let mapping = mapping_context(); + let caller = caller_with(vec![ + VPermission::CreateMapper, + VPermission::ManageGroupMembershipsAll, + VPermission::CreateGroup, + ]); + + let current = NewMapper { + rule: json!({ "rule": "default", "groups": ["engineering"] }), + ..mapper(vec![]) + }; + assert!( + mapping + .add_mapper(&caller, &visible, ¤t) + .await + .is_ok(), + "the caller must be able to create the rule in the current shape" + ); + + for rule in [ + json!({ + "rule": "default", + "permissions": serde_json::to_value(Permissions::::from(vec![VPermission::CreateGroup])).unwrap(), + "groups": ["engineering"], + }), + json!({ "rule": "default" }), + ] { + let new_mapper = NewMapper { + rule: rule.clone(), + ..mapper(vec![]) + }; + let refused = mapping.add_mapper(&caller, &visible, &new_mapper).await; + assert!( + matches!(refused, Err(AddMapperError::InvalidRule)), + "{rule}" + ); + } + } +} diff --git a/v-api/src/context/mod.rs b/v-api/src/context/mod.rs index 6481e94e..72c8795a 100644 --- a/v-api/src/context/mod.rs +++ b/v-api/src/context/mod.rs @@ -24,7 +24,7 @@ use v_model::saga::{ }; use v_model::{ AccessGroup, AccessGroupId, AccessGroupSource, ApiUserInfo, ApiUserProvider, LinkRequest, - Mapper, MapperSource, NewApiUser, NewApiUserProvider, NewLinkRequest, Permissions, UserId, + Mapper, MapperSource, NewApiUserProvider, NewLinkRequest, OAuthClientId, Permissions, UserId, UserProviderId, permissions::{Caller, Permission}, storage::{ @@ -32,7 +32,8 @@ use v_model::{ ApiUserContactEmailStore, ApiUserFilter, ApiUserProviderFilter, ApiUserProviderStore, ApiUserStore, LinkRequestStore, ListPagination, LoginAttemptStore, MagicLinkAttemptStore, MagicLinkRedirectUriStore, MagicLinkSecretStore, MagicLinkStore, MapperEventStore, - MapperStore, OAuthClientRedirectUriStore, OAuthClientSecretStore, OAuthClientStore, + MapperStore, OAuthClientAssertionStore, OAuthClientKeyStore, OAuthClientRedirectUriStore, + OAuthClientSecretStore, OAuthClientStore, ServiceAccountStore, ServiceAccountTokenStore, StoreError, postgres::{PostgresError, PostgresStore}, }, @@ -41,9 +42,12 @@ use v_model::{ use crate::{ authn::{ AuthError, AuthToken, Sign, SigningKeyError, VerificationResult, Verify, - jwt::{Claims, DEFAULT_JWT_EXPIRATION, JwtSigner, JwtSignerError}, + client_assertion::AssertionPolicy, + jwt::{ + DEFAULT_JWT_EXPIRATION, JwtSigner, JwtSignerError, ServiceAccountClaims, UserClaims, + }, }, - config::{JwtConfig, ResolvedAsymmetricKey}, + config::{ClientCredentialsConfig, JwtConfig, ResolvedAsymmetricKey}, endpoints::login::{ UserInfo, oauth::{ @@ -53,7 +57,7 @@ use crate::{ error::ApiError, mapper::DefaultMappingEngine, permissions::{VAppPermission, VPermission}, - response::{OptionalResource, ResourceErrorInner}, + response::ResourceErrorInner, util::response::{ ResourceResult, client_error, internal_error, resource_error, resource_restricted, }, @@ -71,7 +75,10 @@ pub use magic_link::{MagicLinkContext, MagicLinkMessage, MagicLinkTarget}; pub mod mapping; pub use mapping::MappingContext; pub mod oauth; -pub use oauth::{OAuthContext, OAuthError}; +pub use oauth::{ + ClientAuthenticationError, OAuthContext, OAuthError, RegisteredServiceAccountToken, + ServiceAccountCallerError, +}; #[cfg(feature = "sagas")] pub mod saga; #[cfg(feature = "sagas")] @@ -90,6 +97,10 @@ pub trait VApiStorage: + OAuthClientStore + OAuthClientSecretStore + OAuthClientRedirectUriStore + + OAuthClientKeyStore + + OAuthClientAssertionStore + + ServiceAccountStore

+ + ServiceAccountTokenStore + AccessGroupStore

+ MapperStore + MapperEventStore @@ -118,6 +129,10 @@ where + OAuthClientStore + OAuthClientSecretStore + OAuthClientRedirectUriStore + + OAuthClientKeyStore + + OAuthClientAssertionStore + + ServiceAccountStore

+ + ServiceAccountTokenStore + AccessGroupStore

+ MapperStore + MapperEventStore @@ -145,6 +160,10 @@ pub trait VApiStorage: + OAuthClientStore + OAuthClientSecretStore + OAuthClientRedirectUriStore + + OAuthClientKeyStore + + OAuthClientAssertionStore + + ServiceAccountStore

+ + ServiceAccountTokenStore + AccessGroupStore

+ MapperStore + MapperEventStore @@ -171,6 +190,10 @@ where + OAuthClientStore + OAuthClientSecretStore + OAuthClientRedirectUriStore + + OAuthClientKeyStore + + OAuthClientAssertionStore + + ServiceAccountStore

+ + ServiceAccountTokenStore + AccessGroupStore

+ MapperStore + MapperEventStore @@ -187,6 +210,7 @@ where pub struct VContext { public_url: String, + client_credentials: ClientCredentialsConfig, storage: Arc>, auth: AuthContext, pub group: GroupContext, @@ -254,6 +278,8 @@ pub enum VContextCallerError { Auth(#[from] AuthError), #[error(transparent)] Caller(#[from] UserContextError), + #[error(transparent)] + ServiceAccount(#[from] ServiceAccountCallerError), } impl From for HttpError { @@ -261,6 +287,25 @@ impl From for HttpError { match value { VContextCallerError::Auth(inner) => inner.into(), VContextCallerError::Caller(inner) => inner.into(), + VContextCallerError::ServiceAccount(inner) => inner.into(), + } + } +} + +impl From for HttpError { + fn from(error: ServiceAccountCallerError) -> Self { + tracing::info!(?error, "Failed to authenticate service account"); + + match error { + ServiceAccountCallerError::FailedToAuthenticate + | ServiceAccountCallerError::InvalidToken => client_error( + ClientErrorStatusCode::UNAUTHORIZED, + "Failed to authenticate", + ), + ServiceAccountCallerError::Scope(_) => { + client_error(ClientErrorStatusCode::BAD_REQUEST, "Invalid scope") + } + ServiceAccountCallerError::Storage(_) => internal_error("Internal storage failed"), } } } @@ -423,15 +468,51 @@ where self } + pub fn client_assertion_policy(&self) -> AssertionPolicy { + AssertionPolicy { + audience: self.issuer(), + now: Utc::now().timestamp(), + max_lifetime: self.client_credentials.max_assertion_lifetime, + } + } + + pub async fn generate_service_account_token( + &self, + caller: &Caller, + client_id: &TypedUuid, + scope: Vec, + ) -> ResourceResult { + let expires_at = + Utc::now() + TimeDelta::try_seconds(self.client_credentials.token_expiration).unwrap(); + let claims = ServiceAccountClaims::new(self, None, client_id, scope, expires_at); + let token = self + .oauth + .register_service_account_token(caller, self.jwt_signer(), &claims) + .await?; + + tracing::info!(?client_id, "Generated service account token"); + + Ok(token) + } + pub fn generate_claims( &self, api_user: &TypedUuid, api_user_provider: &TypedUuid, + client_id: Uuid, scope: Vec, - ) -> Claims { + ) -> UserClaims { let expires_at = Utc::now() + TimeDelta::try_seconds(self.auth.default_jwt_expiration()).unwrap(); - Claims::new(self, None, api_user, api_user_provider, scope, expires_at) + UserClaims::new( + self, + None, + api_user, + api_user_provider, + client_id, + scope, + expires_at, + ) } pub fn insert_oauth_provider( @@ -462,7 +543,12 @@ where auth: Option<&AuthToken>, ) -> Result, VContextCallerError> { Ok(match auth { - Some(token) => { + Some(AuthToken::ServiceAccount(jwt)) => { + self.oauth + .get_caller(&self.builtin_registration_user(), &jwt.claims) + .await? + } + Some(AuthToken::User(token)) => { self.user .get_caller(&self.builtin_registration_user(), &self.auth, token) .await? @@ -513,18 +599,21 @@ where } }; - let (mapped_permissions, mapped_groups) = self + let visible_groups = self + .group + .list_groups(caller, AccessGroupFilter::default()) + .await + .inner_err_into()?; + let mapped_groups = self .mapping - .get_mapped_fields(caller, &info, user_id) + .get_mapped_fields(caller, &visible_groups, &info, user_id) .await .inner_err_into()?; - tracing::debug!(?mapped_permissions, "Computed mapping permissions"); - tracing::debug!(?mapped_groups, "Computed mapped groups"); + tracing::debug!(?mapped_groups, "Computed mapped fields"); if is_new_user { tracing::info!( - ?mapped_permissions, ?mapped_groups, "Did not find any existing users. Registering a new user." ); @@ -545,7 +634,7 @@ where let user = self .user - .create_api_user(caller, user_id, mapped_permissions, groups) + .create_api_user(caller, user_id, Permissions::default(), groups) .await .inner_err_into()?; @@ -588,12 +677,6 @@ where tracing::info!(?provider.id, ?provider.user_id, "Updating found user permissions and groups"); - // Add mapped permissions to the existing user - self.user - .add_permissions_to_user(caller, &provider.user_id, mapped_permissions) - .await - .inner_err_into()?; - // Add mapped groups to the existing user for group_id in &mapped_groups { self.add_api_user_to_group(caller, &provider.user_id, group_id) @@ -613,20 +696,20 @@ where } } + /// Issues an access token to a user through the named client pub async fn generate_access_token( &self, caller: &Caller, api_user: &TypedUuid, api_user_provider: &TypedUuid, + client_id: Uuid, scope: Vec, - ) -> ResourceResult { - let claims = self.generate_claims(api_user, api_user_provider, scope); + ) -> Result { + let claims = self.generate_claims(api_user, api_user_provider, client_id, scope); let token = self .user .register_access_token(caller, self.jwt_signer(), api_user, &claims) - .await - // TODO: FIXME - .unwrap(); + .await?; tracing::info!(api_user_id = ?api_user, "Generated access token"); @@ -659,40 +742,9 @@ where group_id: &TypedUuid, ) -> ResourceResult, StoreError> { let group = self.group.get_group(caller, group_id).await?; - let can_manage_membership = - caller.can(&VPermission::ManageGroupMembership(*group_id).into()); - let can_grant_permissions = caller.can_grant_all(&group.permissions); - - if !can_manage_membership || !can_grant_permissions { - // This check runs on every login for mapper matched groups. Denials fail the - // entire login, so record exactly which check failed and for which group. - tracing::warn!( - caller = ?caller.id, - ?group_id, - group_name = ?group.name, - can_manage_membership, - can_grant_permissions, - "Caller is not permitted to add user to group" - ); - } - - if can_manage_membership && can_grant_permissions { - // TODO: This needs to be wrapped in a transaction. That requires reworking the way the - // store traits are handled. Ideally we could have an API that still abstracts away the - // underlying connection management while allowing for transactions. Possibly something - // that takes a closure and passes in a connection that implements all of the expected - // data store traits - let info = ApiUserStore::get(&*self.storage, api_user_id, false) - .await - .optional()?; - - let mut update: NewApiUser = info.user.into(); - update.groups.insert(*group_id); - - Ok(ApiUserStore::upsert(&*self.storage, update).await?) - } else { - resource_restricted() - } + self.user + .add_user_to_group(caller, api_user_id, &group) + .await } pub async fn remove_api_user_from_group( @@ -701,23 +753,10 @@ where api_user_id: &TypedUuid, group_id: &TypedUuid, ) -> ResourceResult, StoreError> { - if caller.can(&VPermission::ManageGroupMembership(*group_id).into()) { - // TODO: This needs to be wrapped in a transaction. That requires reworking the way the - // store traits are handled. Ideally we could have an API that still abstracts away the - // underlying connection management while allowing for transactions. Possibly something - // that takes a closure and passes in a connection that implements all of the expected - // data store traits - let info = ApiUserStore::get(&*self.storage, api_user_id, false) - .await - .optional()?; - - let mut update: NewApiUser = info.user.into(); - update.groups.retain(|id| id != group_id); - - Ok(ApiUserStore::upsert(&*self.storage, update).await?) - } else { - resource_restricted() - } + let group = self.group.get_group(caller, group_id).await?; + self.user + .remove_user_from_group(caller, api_user_id, &group) + .await } pub async fn complete_link_request( @@ -832,6 +871,7 @@ pub struct VContextBuilder { param_path: Option, service_name: Option, jwt_expiration: Option, + client_credentials: Option, public_url: Option, storage: Option>>, storage_url: Option, @@ -861,6 +901,7 @@ where param_path: None, service_name: None, jwt_expiration: None, + client_credentials: None, public_url: None, storage: None, storage_url: None, @@ -888,6 +929,11 @@ where self } + pub fn with_client_credentials(mut self, config: ClientCredentialsConfig) -> Self { + self.client_credentials = Some(config); + self + } + pub fn with_public_url(mut self, url: String) -> Self { self.public_url = Some(url); self @@ -1061,6 +1107,7 @@ where created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, } }) .collect(); @@ -1133,10 +1180,7 @@ where } let mut mapping_ctx = MappingContext::new(storage.clone()); - mapping_ctx.set_engine(Some(Arc::new(DefaultMappingEngine::new( - auth_ctx.builtin_registration_user(), - group_ctx.clone(), - )))); + mapping_ctx.set_engine(Some(Arc::new(DefaultMappingEngine))); // Convert preset mapper configs into Mapper structs with deterministic IDs let preset_mappers: Vec = self @@ -1167,7 +1211,7 @@ where "Loaded preset mappers from configuration" ); - // Validate all preset mappers before setting them + // Validate all preset mappers before setting them. for mapper in &preset_mappers { if !mapping_ctx.validate(&mapper.rule) { return Err(VContextBuilderError::InvalidMapperRule( @@ -1209,6 +1253,7 @@ where Ok(VContext { public_url, + client_credentials: self.client_credentials.unwrap_or_default(), storage: storage.clone(), auth: auth_ctx, group: group_ctx, @@ -1233,21 +1278,23 @@ mod tests { use uuid::Uuid; use v_model::{ AccessGroup, AccessGroupId, AccessGroupSource, AccessToken, AccessTokenId, ApiUser, - ApiUserInfo, ApiUserProvider, UserId, - permissions::{Caller, Permissions}, + ApiUserInfo, ApiUserProvider, OAuthClient, OAuthClientId, ServiceAccount, + ServiceAccountToken, ServiceAccountTokenId, UserId, + permissions::{Caller, Permissions, Principal}, storage::{ AccessGroupFilter, ListPagination, MockAccessGroupStore, MockAccessTokenStore, - MockApiUserStore, StoreError, + MockApiUserStore, MockOAuthClientStore, MockServiceAccountStore, + MockServiceAccountTokenStore, StoreError, }, }; use crate::{ VContextBuilder, VContextBuilderError, authn::{ - AuthToken, - jwt::{Claims, Jwt}, + AuthToken, UserToken, + jwt::{Jwt, ServiceAccountClaims, TokenClaims, UserClaims}, }, - context::user::UserContextError, + context::{ServiceAccountCallerError, user::UserContextError}, permissions::VPermission, util::tests::{MockKey, mock_key}, }; @@ -1270,6 +1317,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }; let provider = ApiUserProvider { @@ -1285,18 +1333,21 @@ mod tests { }; let user_token = ctx - .sign_jwt(&Claims::new( + .sign_jwt(&UserClaims::new( ctx, Some(token_id), &user.id, &provider.id, + Uuid::new_v4(), scope, Utc::now().add(TimeDelta::try_seconds(300).unwrap()), )) .await .unwrap(); - AuthToken::Jwt(Jwt::new(ctx, &user_token).await.unwrap()) + AuthToken::User(UserToken::Session( + Jwt::new(ctx, &user_token).await.unwrap(), + )) } #[tokio::test] @@ -1314,6 +1365,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }; let pagination = ListPagination::unlimited(); let mut group_store = MockAccessGroupStore::new(); @@ -1340,6 +1392,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }, email: None, providers: vec![], @@ -1446,6 +1499,281 @@ mod tests { } } + /// Signs a token for a service account and reads it back the way a request would + async fn sign_and_read( + ctx: &VContext, + claims: &ServiceAccountClaims, + ) -> AuthToken { + let token = ctx.sign_jwt(claims).await.unwrap(); + Jwt::::new(ctx, &token).await.unwrap().into() + } + + async fn service_account_token( + ctx: &VContext, + token_id: TypedUuid, + client_id: TypedUuid, + scope: &[&str], + ) -> AuthToken { + sign_and_read( + ctx, + &ServiceAccountClaims::new( + ctx, + Some(token_id), + &client_id, + scope.iter().map(|scope| scope.to_string()).collect(), + Utc::now().add(TimeDelta::try_seconds(300).unwrap()), + ), + ) + .await + } + + /// Storage holding one live client and its service account. Tokens are known only when they + /// are listed in `tokens`, as the token id and the client it was issued to. + async fn service_account_ctx( + client_id: TypedUuid, + permissions: Option>, + tokens: Vec<(TypedUuid, TypedUuid)>, + ) -> VContext { + let mut client_store = MockOAuthClientStore::new(); + client_store.expect_get().returning(move |id, deleted| { + Ok((id == &client_id && !deleted).then(|| OAuthClient { + id: *id, + secrets: vec![], + redirect_uris: vec![], + keys: vec![], + created_at: Utc::now(), + deleted_at: None, + })) + }); + + let mut account_store = MockServiceAccountStore::new(); + account_store.expect_get().returning(move |id| { + Ok(permissions.clone().map(|permissions| ServiceAccount { + id: *id, + permissions, + created_at: Utc::now(), + updated_at: Utc::now(), + generation: 0, + })) + }); + + let mut token_store = MockServiceAccountTokenStore::new(); + token_store.expect_get().returning(move |id, _| { + Ok(tokens.iter().find(|(token_id, _)| token_id == id).map( + |(token_id, oauth_client_id)| ServiceAccountToken { + id: *token_id, + oauth_client_id: *oauth_client_id, + expires_at: Utc::now() + TimeDelta::try_seconds(300).unwrap(), + revoked_at: None, + created_at: Utc::now(), + updated_at: Utc::now(), + }, + )) + }); + + let mut storage = MockStorage::new(); + storage.oauth_client_store = Some(Arc::new(client_store)); + storage.service_account_store = Some(Arc::new(account_store)); + storage.service_account_token_store = Some(Arc::new(token_store)); + + mock_context(Arc::new(storage)).await + } + + fn assert_invalid_service_account_token( + result: Result, VContextCallerError>, + ) { + assert!( + matches!( + result, + Err(VContextCallerError::ServiceAccount( + ServiceAccountCallerError::InvalidToken + )) + ), + "{result:?}" + ); + } + + /// Each kind of token is read back as the kind of principal it was issued for + #[tokio::test] + async fn tokens_are_read_as_the_principal_they_were_issued_for() { + let ctx = mock_context(Arc::new(MockStorage::new())).await; + + let service = + service_account_token(&ctx, TypedUuid::new_v4(), TypedUuid::new_v4(), &[]).await; + assert!(matches!(service, AuthToken::ServiceAccount(_))); + + let user_token = ctx + .sign_jwt(&UserClaims::new( + &ctx, + None, + &TypedUuid::new_v4(), + &TypedUuid::new_v4(), + Uuid::new_v4(), + vec![], + Utc::now().add(TimeDelta::try_seconds(300).unwrap()), + )) + .await + .unwrap(); + let user: AuthToken = Jwt::::new(&ctx, &user_token) + .await + .unwrap() + .into(); + assert!(matches!(user, AuthToken::User(UserToken::Session(_)))); + } + + /// A service account caller holds the permissions of its service account, and is never a user + #[tokio::test] + async fn a_service_account_token_resolves_to_the_service_account() { + let client_id = TypedUuid::new_v4(); + let token_id = TypedUuid::new_v4(); + let held: Permissions = + vec![VPermission::CreateGroup, VPermission::GetMappersAll].into(); + let ctx = + service_account_ctx(client_id, Some(held.clone()), vec![(token_id, client_id)]).await; + + let token = service_account_token(&ctx, token_id, client_id, &["full"]).await; + let caller = ctx.get_caller_from_token(Some(&token)).await.unwrap(); + + assert_eq!(Principal::ServiceAccount(client_id), caller.principal); + assert_eq!(None, caller.user_id()); + assert_eq!(held, caller.permissions); + assert!(caller.extensions.is_empty()); + } + + /// The scope of a token narrows what the service account holds and never adds to it + #[tokio::test] + async fn a_service_account_token_is_narrowed_by_its_scope() { + let client_id = TypedUuid::new_v4(); + let token_id = TypedUuid::new_v4(); + let held: Permissions = + vec![VPermission::CreateGroup, VPermission::GetMappersAll].into(); + let ctx = service_account_ctx(client_id, Some(held), vec![(token_id, client_id)]).await; + + let token = + service_account_token(&ctx, token_id, client_id, &["group:info:w", "user:info:r"]) + .await; + let caller = ctx.get_caller_from_token(Some(&token)).await.unwrap(); + + assert_eq!( + Permissions::::from(vec![VPermission::CreateGroup]), + caller.permissions + ); + + let token = service_account_token(&ctx, token_id, client_id, &[]).await; + let caller = ctx.get_caller_from_token(Some(&token)).await.unwrap(); + assert!(caller.permissions.is_empty()); + } + + /// A client that has never been granted anything resolves to a caller that holds nothing + #[tokio::test] + async fn a_service_account_without_permissions_holds_nothing() { + let client_id = TypedUuid::new_v4(); + let token_id = TypedUuid::new_v4(); + let ctx = service_account_ctx(client_id, None, vec![(token_id, client_id)]).await; + + let token = service_account_token(&ctx, token_id, client_id, &["full"]).await; + let caller = ctx.get_caller_from_token(Some(&token)).await.unwrap(); + + assert_eq!(Principal::ServiceAccount(client_id), caller.principal); + assert!(caller.permissions.is_empty()); + } + + /// Permissions over the holder's own user or joined groups mean nothing without a user record, + /// while value sets still resolve to their values + #[tokio::test] + async fn user_relative_permissions_resolve_to_nothing_for_a_service_account() { + let client_id = TypedUuid::new_v4(); + let token_id = TypedUuid::new_v4(); + let group_id = TypedUuid::new_v4(); + let held: Permissions = vec![ + VPermission::GetApiUserSelf, + VPermission::GetGroupsJoined, + VPermission::ManageGroups([group_id].into()), + ] + .into(); + let ctx = service_account_ctx(client_id, Some(held), vec![(token_id, client_id)]).await; + + let token = service_account_token(&ctx, token_id, client_id, &["full"]).await; + let caller = ctx.get_caller_from_token(Some(&token)).await.unwrap(); + + assert_eq!( + Permissions::::from(vec![VPermission::ManageGroup(group_id)]), + caller.permissions + ); + } + + /// A token that is unknown or revoked, or that was issued to a different client, is refused + #[tokio::test] + async fn a_service_account_token_must_be_known_and_issued_to_the_client() { + let client_id = TypedUuid::new_v4(); + let other_client_id = TypedUuid::new_v4(); + let foreign_token_id = TypedUuid::new_v4(); + let ctx = service_account_ctx( + client_id, + Some(vec![VPermission::CreateGroup].into()), + vec![(foreign_token_id, other_client_id)], + ) + .await; + + let unknown = service_account_token(&ctx, TypedUuid::new_v4(), client_id, &["full"]).await; + assert_invalid_service_account_token(ctx.get_caller_from_token(Some(&unknown)).await); + + let foreign = service_account_token(&ctx, foreign_token_id, client_id, &["full"]).await; + assert_invalid_service_account_token(ctx.get_caller_from_token(Some(&foreign)).await); + } + + /// A token whose subject and client id name different clients is refused + #[tokio::test] + async fn a_service_account_token_must_name_one_client() { + let client_id = TypedUuid::new_v4(); + let token_id = TypedUuid::new_v4(); + let ctx = service_account_ctx( + client_id, + Some(vec![VPermission::CreateGroup].into()), + vec![(token_id, client_id)], + ) + .await; + + let mut claims = ServiceAccountClaims::new( + &ctx, + Some(token_id), + &client_id, + vec!["full".to_string()], + Utc::now().add(TimeDelta::try_seconds(300).unwrap()), + ); + claims.sub = TypedUuid::new_v4(); + let token = sign_and_read(&ctx, &claims).await; + + assert_invalid_service_account_token(ctx.get_caller_from_token(Some(&token)).await); + } + + /// A token for a client that is deleted or does not exist is refused + #[tokio::test] + async fn a_service_account_token_for_a_missing_client_is_refused() { + let client_id = TypedUuid::new_v4(); + let missing_client_id = TypedUuid::new_v4(); + let token_id = TypedUuid::new_v4(); + let ctx = service_account_ctx( + client_id, + Some(vec![VPermission::CreateGroup].into()), + vec![(token_id, missing_client_id)], + ) + .await; + + let token = service_account_token(&ctx, token_id, missing_client_id, &["full"]).await; + let result = ctx.get_caller_from_token(Some(&token)).await; + + assert!( + matches!( + result, + Err(VContextCallerError::ServiceAccount( + ServiceAccountCallerError::FailedToAuthenticate + )) + ), + "{result:?}" + ); + } + #[tokio::test] async fn test_preset_group_membership_grants_permissions() { let mut storage = MockStorage::new(); @@ -1466,6 +1794,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }, email: None, providers: vec![], @@ -1539,6 +1868,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }, email: None, providers: vec![], @@ -1549,8 +1879,8 @@ mod tests { .expect_get() .with(eq(user_id), eq(false)) .returning(move |_, _| Ok(Some(user.clone()))); - user_store.expect_upsert().returning(|update| { - Ok(ApiUserInfo { + user_store.expect_update().returning(|update, _| { + Ok(Some(ApiUserInfo { user: ApiUser { id: update.id, permissions: update.permissions, @@ -1558,10 +1888,11 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }, email: None, providers: vec![], - }) + })) }); let mut group_store = MockAccessGroupStore::new(); @@ -1582,8 +1913,9 @@ mod tests { }; let caller = Caller { - id: user_id, + principal: Principal::User(user_id), permissions: vec![ + VPermission::GetApiUsersAll, VPermission::GetGroupsAll, VPermission::ManageGroupMembershipsAll, // Required to grant the permissions held by the group @@ -1600,6 +1932,27 @@ mod tests { .unwrap(); assert_eq!(BTreeSet::from([group_id]), added.user.groups); + // Leaving the group takes away CreateGroup, which this caller can not grant, so it may + // not remove the user even though it can manage the group's membership + let cannot_grant = Caller { + principal: Principal::User(user_id), + permissions: vec![ + VPermission::GetApiUsersAll, + VPermission::GetGroupsAll, + VPermission::ManageGroupMembershipsAll, + ] + .into(), + extensions: Default::default(), + }; + let ctx = ctx_with_memberships(BTreeSet::from([group_id])).await; + let refused = ctx + .remove_api_user_from_group(&cannot_grant, &user_id, &group_id) + .await; + assert!(matches!( + refused, + Err(crate::response::ResourceError::Restricted) + )); + let ctx = ctx_with_memberships(BTreeSet::from([group_id])).await; let removed = ctx .remove_api_user_from_group(&caller, &user_id, &group_id) @@ -1649,6 +2002,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }]) }); @@ -1769,7 +2123,7 @@ pub(crate) mod test_mocks { NewApiUser, NewApiUserContactEmail, NewApiUserProvider, NewLoginAttempt, NewMagicLink, NewMagicLinkAttempt, NewMagicLinkRedirectUri, NewMagicLinkSecret, NewMapper, OAuthClientId, OAuthRedirectUriId, OAuthSecretId, UserContactEmailId, UserId, UserProviderId, - permissions::Caller, + permissions::{Caller, Principal}, schema_ext::MagicLinkAttemptState, storage::{ AccessGroupStore, AccessTokenStore, ApiKeyStore, ApiUserContactEmailStore, @@ -1780,9 +2134,12 @@ pub(crate) mod test_mocks { MockApiUserContactEmailStore, MockApiUserProviderStore, MockApiUserStore, MockLinkRequestStore, MockLoginAttemptStore, MockMagicLinkAttemptStore, MockMagicLinkRedirectUriStore, MockMagicLinkSecretStore, MockMagicLinkStore, - MockMapperEventStore, MockMapperStore, MockOAuthClientRedirectUriStore, - MockOAuthClientSecretStore, MockOAuthClientStore, OAuthClientRedirectUriStore, - OAuthClientSecretStore, OAuthClientStore, StoreError, + MockMapperEventStore, MockMapperStore, MockOAuthClientAssertionStore, + MockOAuthClientKeyStore, MockOAuthClientRedirectUriStore, MockOAuthClientSecretStore, + MockOAuthClientStore, MockServiceAccountStore, MockServiceAccountTokenStore, + OAuthClientAssertionStore, OAuthClientKeyFilter, OAuthClientKeyStore, + OAuthClientRedirectUriStore, OAuthClientSecretStore, OAuthClientStore, + ServiceAccountStore, ServiceAccountTokenStore, StoreError, }, }; @@ -1832,10 +2189,7 @@ pub(crate) mod test_mocks { ) -> VContext { let mut ctx = build_ctx_with_groups(storage, groups).await.unwrap(); - let mapping_engine = Arc::new(DefaultMappingEngine::new( - ctx.builtin_registration_user(), - ctx.group.clone(), - )); + let mapping_engine = Arc::new(DefaultMappingEngine); ctx.mapping.set_engine(Some(mapping_engine)); ctx.auth.insert_oauth_provider( @@ -1893,6 +2247,10 @@ pub(crate) mod test_mocks { pub oauth_client_store: Option>, pub oauth_client_secret_store: Option>, pub oauth_client_redirect_uri_store: Option>, + pub oauth_client_key_store: Option>, + pub oauth_client_assertion_store: Option>, + pub service_account_store: Option>>, + pub service_account_token_store: Option>, pub access_group_store: Option>>, pub mapper_store: Option>, pub mapper_event_store: Option>, @@ -1919,6 +2277,10 @@ pub(crate) mod test_mocks { oauth_client_store: None, oauth_client_secret_store: None, oauth_client_redirect_uri_store: None, + oauth_client_key_store: None, + oauth_client_assertion_store: None, + service_account_store: None, + service_account_token_store: None, access_group_store: None, mapper_store: None, mapper_event_store: None, @@ -1958,11 +2320,24 @@ pub(crate) mod test_mocks { .await } - async fn upsert( + async fn create( &self, api_user: NewApiUser, ) -> Result, v_model::storage::StoreError> { - self.api_user_store.as_ref().unwrap().upsert(api_user).await + self.api_user_store.as_ref().unwrap().create(api_user).await + } + + async fn update( + &self, + api_user: NewApiUser, + expected_generation: i64, + ) -> Result>, v_model::storage::StoreError> + { + self.api_user_store + .as_ref() + .unwrap() + .update(api_user, expected_generation) + .await } async fn delete( @@ -2307,6 +2682,159 @@ pub(crate) mod test_mocks { } } + #[async_trait] + impl OAuthClientKeyStore for MockStorage { + async fn get( + &self, + id: &TypedUuid, + deleted: bool, + ) -> Result, StoreError> { + self.oauth_client_key_store + .as_ref() + .unwrap() + .get(id, deleted) + .await + } + + async fn list( + &self, + filter: OAuthClientKeyFilter, + pagination: &ListPagination, + ) -> Result, StoreError> { + self.oauth_client_key_store + .as_ref() + .unwrap() + .list(filter, pagination) + .await + } + + async fn insert( + &self, + key: v_model::NewOAuthClientKey, + ) -> Result { + self.oauth_client_key_store + .as_ref() + .unwrap() + .insert(key) + .await + } + + async fn delete( + &self, + id: &TypedUuid, + ) -> Result, StoreError> { + self.oauth_client_key_store + .as_ref() + .unwrap() + .delete(id) + .await + } + } + + #[async_trait] + impl OAuthClientAssertionStore for MockStorage { + async fn record( + &self, + assertion: v_model::NewOAuthClientAssertion, + ) -> Result { + self.oauth_client_assertion_store + .as_ref() + .unwrap() + .record(assertion) + .await + } + + async fn delete_expired(&self, before: chrono::DateTime) -> Result { + self.oauth_client_assertion_store + .as_ref() + .unwrap() + .delete_expired(before) + .await + } + } + + #[async_trait] + impl ServiceAccountStore for MockStorage { + async fn get( + &self, + id: &TypedUuid, + ) -> Result>, StoreError> { + self.service_account_store.as_ref().unwrap().get(id).await + } + + async fn create( + &self, + account: v_model::NewServiceAccount, + ) -> Result, StoreError> { + self.service_account_store + .as_ref() + .unwrap() + .create(account) + .await + } + + async fn update( + &self, + account: v_model::NewServiceAccount, + expected_generation: i64, + ) -> Result>, StoreError> { + self.service_account_store + .as_ref() + .unwrap() + .update(account, expected_generation) + .await + } + } + + #[async_trait] + impl ServiceAccountTokenStore for MockStorage { + async fn get( + &self, + id: &TypedUuid, + revoked: bool, + ) -> Result, StoreError> { + self.service_account_token_store + .as_ref() + .unwrap() + .get(id, revoked) + .await + } + + async fn list( + &self, + filter: v_model::storage::ServiceAccountTokenFilter, + pagination: &ListPagination, + ) -> Result, StoreError> { + self.service_account_token_store + .as_ref() + .unwrap() + .list(filter, pagination) + .await + } + + async fn create( + &self, + token: v_model::NewServiceAccountToken, + ) -> Result { + self.service_account_token_store + .as_ref() + .unwrap() + .create(token) + .await + } + + async fn revoke( + &self, + id: &TypedUuid, + ) -> Result, StoreError> { + self.service_account_token_store + .as_ref() + .unwrap() + .revoke(id) + .await + } + } + #[async_trait] impl AccessGroupStore for MockStorage { async fn get( @@ -2345,6 +2873,19 @@ pub(crate) mod test_mocks { .await } + async fn update( + &self, + group: &NewAccessGroup, + expected_generation: i64, + ) -> Result>, v_model::storage::StoreError> + { + self.access_group_store + .as_ref() + .unwrap() + .update(group, expected_generation) + .await + } + async fn delete( &self, id: &TypedUuid, @@ -2720,12 +3261,13 @@ pub(crate) mod test_mocks { let result = ctx .generate_access_token( &Caller { - id: TypedUuid::from_untyped_uuid(Uuid::new_v4()), + principal: Principal::User(TypedUuid::from_untyped_uuid(Uuid::new_v4())), permissions: vec![VPermission::CreateAccessToken].into(), extensions: HashMap::default(), }, &api_user_id, &api_user_provider_id, + Uuid::new_v4(), vec![], ) .await; diff --git a/v-api/src/context/oauth.rs b/v-api/src/context/oauth.rs index 9b30dfae..ef6e17ff 100644 --- a/v-api/src/context/oauth.rs +++ b/v-api/src/context/oauth.rs @@ -2,32 +2,91 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. +use chrono::{DateTime, Utc}; use newtype_uuid::TypedUuid; -use std::sync::Arc; +use std::{collections::HashMap, sync::Arc}; use thiserror::Error; use v_model::{ - NewOAuthClient, NewOAuthClientRedirectUri, NewOAuthClientSecret, OAuthClient, OAuthClientId, - OAuthClientRedirectUri, OAuthClientSecret, OAuthRedirectUriId, OAuthSecretId, - permissions::Caller, + NewOAuthClient, NewOAuthClientAssertion, NewOAuthClientKey, NewOAuthClientRedirectUri, + NewOAuthClientSecret, NewServiceAccount, NewServiceAccountToken, OAuthClient, OAuthClientId, + OAuthClientKey, OAuthClientKeyId, OAuthClientRedirectUri, OAuthClientSecret, + OAuthRedirectUriId, OAuthSecretId, Permissions, ServiceAccountToken, ServiceAccountTokenId, + jwk::PublicJwk, + permissions::{AsScope, Caller, PermissionError, PermissionStorage, Principal}, storage::{ - ListPagination, OAuthClientFilter, OAuthClientRedirectUriStore, OAuthClientSecretStore, - OAuthClientStore, StoreError, + ListPagination, OAuthClientAssertionStore, OAuthClientFilter, OAuthClientKeyFilter, + OAuthClientKeyStore, OAuthClientRedirectUriStore, OAuthClientSecretStore, OAuthClientStore, + ServiceAccountStore, ServiceAccountTokenFilter, ServiceAccountTokenStore, StoreError, }, }; use crate::{ VApiStorage, + authn::{ + client_assertion::{AssertionError, AssertionPolicy, CLOCK_SKEW, UnverifiedAssertion}, + client_key::{ClientKeyError, JwkThumbprint}, + jwt::{JwtSigner, JwtSignerError, ServiceAccountClaims}, + }, permissions::{VAppPermission, VPermission}, - response::{OptionalResource, ResourceError, ResourceResult, resource_restricted}, + response::{ + OptionalResource, ResourceError, ResourceResult, resource_conflict, resource_restricted, + }, util::{RedirectUrlError, parse_redirect_url}, }; #[derive(Debug, Error)] pub enum OAuthError { + #[error("Invalid client key")] + ClientKey(#[from] ClientKeyError), #[error("Invalid redirect URI")] RedirectUri(#[from] RedirectUrlError), #[error("Storage layer error")] StoreError(#[from] StoreError), + #[error("Failed to sign token")] + Jwt(#[from] JwtSignerError), +} + +#[derive(Debug, Error)] +pub enum ClientAuthenticationError { + #[error(transparent)] + Assertion(#[from] AssertionError), + #[error("Assertion names a client that does not exist")] + UnknownClient, + #[error("Assertion names a key that the client does not hold")] + UnknownKey, + #[error("Request names a different client than the one that signed the assertion")] + ClientMismatch, + #[error("Assertion has already been used")] + Replay, + #[error("Caller is not allowed to authenticate clients")] + Restricted, + #[error("Inner storage failure: {0}")] + Storage(#[from] StoreError), +} + +pub struct RegisteredServiceAccountToken { + pub token: ServiceAccountToken, + pub signed_token: String, + pub expires_in: i64, +} + +#[derive(Debug, Error)] +pub enum ServiceAccountCallerError { + #[error("Failed to authenticate service account")] + FailedToAuthenticate, + #[error("Service account token has an unknown id, has been revoked, or names the wrong client")] + InvalidToken, + #[error("Invalid scope: {0}")] + Scope(#[from] PermissionError), + #[error("Inner storage failure: {0}")] + Storage(#[from] StoreError), +} + +/// A change to the permissions a client's service account holds. Each kind of change carries what +/// is needed to check the caller's authority to make it. +enum ServiceAccountChange<'a, T> { + AddPermission(T), + RemovePermission(&'a T), } #[derive(Clone)] @@ -83,7 +142,7 @@ where id: None, deleted: false, }, - &ListPagination::default(), + &ListPagination::unlimited(), ) .await?; @@ -92,6 +151,430 @@ where Ok(clients) } + /// Registers the public half of a key pair whose private key the client keeps and signs its + /// client credentials assertions with. Assertions are verified against the registered public + /// key. + pub async fn add_oauth_client_key( + &self, + caller: &Caller, + client_id: &TypedUuid, + jwk: PublicJwk, + ) -> ResourceResult { + let client = self.get_oauth_client(caller, client_id).await?; + + if caller.can(&VPermission::ManageOAuthClient(client.id).into()) { + let thumbprint = jwk + .thumbprint() + .map_err(|err| ResourceError::InternalError(OAuthError::ClientKey(err)))?; + + Ok(OAuthClientKeyStore::insert( + &*self.storage, + NewOAuthClientKey { + id: TypedUuid::new_v4(), + oauth_client_id: client.id, + thumbprint, + jwk, + }, + ) + .await?) + } else { + resource_restricted() + } + } + + /// Removes one of the client's public keys, so that assertions signed with the matching + /// private key are no longer accepted. This does not revoke any existing tokens issued against + /// this key. + pub async fn delete_oauth_client_key( + &self, + caller: &Caller, + client_id: &TypedUuid, + key_id: &TypedUuid, + ) -> ResourceResult { + let client = self.get_oauth_client(caller, client_id).await?; + + if !client.keys.iter().any(|key| &key.id == key_id) { + Err(ResourceError::DoesNotExist) + } else if caller.can(&VPermission::ManageOAuthClient(client.id).into()) { + OAuthClientKeyStore::delete(&*self.storage, key_id) + .await + .optional() + } else { + resource_restricted() + } + } + + /// Authenticates a client by the JWT assertion it presented under RFC 7523 §2.2. The assertion + /// is only verified against the key on that client whose thumbprint matches the + /// assertion's key id. By recording the assertion we are "accepting" it, after which it may + /// never be accepted again. + pub async fn authenticate_client( + &self, + caller: &Caller, + assertion: &str, + requested_client: Option<&TypedUuid>, + policy: &AssertionPolicy, + ) -> Result { + let unverified = UnverifiedAssertion::parse(assertion)?; + let key = OAuthClientKeyStore::list( + &*self.storage, + OAuthClientKeyFilter { + thumbprint: Some(vec![unverified.untrusted_kid().to_string()]), + ..Default::default() + }, + &ListPagination::latest(), + ) + .await? + .pop(); + + if let Some(key) = key { + let claims = unverified.verify(&key.jwk, policy)?; + if key.oauth_client_id != claims.iss { + Err(ClientAuthenticationError::UnknownKey) + } else if requested_client.is_some_and(|requested| requested != &claims.iss) { + Err(ClientAuthenticationError::ClientMismatch) + } else { + let client = self + .get_oauth_client(caller, &claims.iss) + .await + .map_err(|err| match err { + ResourceError::DoesNotExist => ClientAuthenticationError::UnknownClient, + ResourceError::InternalError(OAuthError::StoreError(err)) => { + ClientAuthenticationError::Storage(err) + } + err => { + tracing::error!( + ?err, + "Failed to read the client named by an assertion" + ); + ClientAuthenticationError::Restricted + } + })?; + + if caller.can(&VPermission::ManageOAuthClient(client.id).into()) { + OAuthClientAssertionStore::record( + &*self.storage, + NewOAuthClientAssertion { + oauth_client_id: client.id, + jti: claims.jti, + expires_at: DateTime::::from_timestamp( + claims.exp.saturating_add(CLOCK_SKEW), + 0, + ) + .unwrap_or(DateTime::::MAX_UTC), + }, + ) + .await + .map_err(|err| match err { + StoreError::Conflict => ClientAuthenticationError::Replay, + err => ClientAuthenticationError::Storage(err), + })?; + + tracing::info!(client_id = ?client.id, kid = ?key.thumbprint, "Authenticated client by assertion"); + + Ok(client) + } else { + Err(ClientAuthenticationError::Restricted) + } + } + } else { + Err(ClientAuthenticationError::UnknownKey) + } + } + + /// List all service account tokens issued to a client that are active. + pub async fn list_service_account_tokens( + &self, + caller: &Caller, + client_id: &TypedUuid, + ) -> ResourceResult, OAuthError> { + let client = self.get_oauth_client(caller, client_id).await?; + + Ok(ServiceAccountTokenStore::list( + &*self.storage, + ServiceAccountTokenFilter { + oauth_client_id: Some(vec![client.id]), + revoked: false, + expired: false, + }, + &ListPagination::unlimited(), + ) + .await?) + } + + /// Revokes one of a client's service account tokens. + pub async fn revoke_service_account_token( + &self, + caller: &Caller, + client_id: &TypedUuid, + token_id: &TypedUuid, + ) -> ResourceResult { + let client = self.get_oauth_client(caller, client_id).await?; + + if !caller.can(&VPermission::ManageOAuthClient(client.id).into()) { + resource_restricted() + } else { + let token = ServiceAccountTokenStore::get(&*self.storage, token_id, false).await?; + + if token.is_some_and(|token| token.oauth_client_id == client.id) { + let revoked = ServiceAccountTokenStore::revoke(&*self.storage, token_id) + .await + .optional()?; + tracing::info!(client_id = ?client.id, ?token_id, "Revoked service account token"); + + Ok(revoked) + } else { + Err(ResourceError::DoesNotExist) + } + } + } + + /// Removes the records of client assertions that can no longer be accepted, returning how many + /// were removed. + pub async fn delete_expired_client_assertions( + &self, + caller: &Caller, + ) -> ResourceResult { + if caller.can(&VPermission::ManageOAuthClientsAll.into()) { + let removed = + OAuthClientAssertionStore::delete_expired(&*self.storage, Utc::now()).await?; + tracing::info!(removed, "Removed expired client assertions"); + + Ok(removed) + } else { + resource_restricted() + } + } + + /// Records and signs an access token for a client acting as its service account. The token is + /// recorded before it is signed, so every token that is handed out can be resolved and + /// revoked. + pub async fn register_service_account_token( + &self, + caller: &Caller, + signer: &JwtSigner, + claims: &ServiceAccountClaims, + ) -> ResourceResult { + if caller.can(&VPermission::CreateAccessToken.into()) { + let client = self.get_oauth_client(caller, &claims.client_id).await?; + let token = ServiceAccountTokenStore::create( + &*self.storage, + NewServiceAccountToken { + id: claims.jti, + oauth_client_id: client.id, + expires_at: DateTime::::from_timestamp(claims.exp, 0) + .unwrap_or(DateTime::::MAX_UTC), + }, + ) + .await?; + + let signed_token = signer + .sign(claims) + .await + .map_err(|err| ResourceError::InternalError(OAuthError::Jwt(err)))?; + + Ok(RegisteredServiceAccountToken { + token, + signed_token, + expires_in: claims.exp - Utc::now().timestamp(), + }) + } else { + resource_restricted() + } + } + + /// The client a service account token was issued to. The token must name the same client as + /// its subject and as its client id. + fn token_client_id( + claims: &ServiceAccountClaims, + ) -> Result, ServiceAccountCallerError> { + if claims.sub == claims.client_id { + Ok(claims.client_id) + } else { + tracing::warn!(sub = ?claims.sub, client_id = ?claims.client_id, "Service account token names two different clients"); + Err(ServiceAccountCallerError::InvalidToken) + } + } + + /// Resolves the caller for a verified service account token. + pub async fn get_caller( + &self, + registration_user: &Caller, + claims: &ServiceAccountClaims, + ) -> Result, ServiceAccountCallerError> { + let client_id = Self::token_client_id(claims)?; + + let client = self + .get_oauth_client(registration_user, &client_id) + .await + .map_err(|err| match err { + ResourceError::InternalError(OAuthError::StoreError(err)) => { + ServiceAccountCallerError::Storage(err) + } + err => { + tracing::info!(?err, ?client_id, "Service account client could not be read"); + ServiceAccountCallerError::FailedToAuthenticate + } + })?; + + // The token must be known, must not have been revoked, and must have been issued to this + // client. From here on the caller is the client the token was issued to. + let token = ServiceAccountTokenStore::get(&*self.storage, &claims.jti, false) + .await? + .filter(|token| token.oauth_client_id == client.id) + .ok_or(ServiceAccountCallerError::InvalidToken)?; + + let held = ServiceAccountStore::get(&*self.storage, &token.oauth_client_id) + .await? + .map(|account| account.permissions.expand_values()) + .unwrap_or_default(); + let extensions = HashMap::new(); + let held = ::expand(&held, None, Some(&held), &extensions); + + let permissions = if claims.scp.iter().any(|scope| scope == "full") { + held + } else { + let scoped = ::from_scope(claims.scp.iter())?; + ::expand(&scoped, None, Some(&held), &extensions) + .intersect(&held) + }; + + let caller = Caller { + principal: Principal::ServiceAccount(token.oauth_client_id), + permissions: permissions.into_iter().collect(), + extensions, + }; + + tracing::info!(?caller.principal, "Resolved service account caller"); + tracing::debug!(?caller.permissions, "Caller permissions"); + + Ok(caller) + } + + pub async fn get_service_account_permissions( + &self, + caller: &Caller, + client_id: &TypedUuid, + ) -> ResourceResult, OAuthError> { + let client = self.get_oauth_client(caller, client_id).await?; + + Ok(ServiceAccountStore::get(&*self.storage, &client.id) + .await? + .map(|account| account.permissions) + .unwrap_or_default()) + } + + /// Grants a permission to the client's service account. + pub async fn add_permission_to_service_account( + &self, + caller: &Caller, + client_id: &TypedUuid, + permission: T, + ) -> ResourceResult, OAuthError> { + self.modify_service_account( + caller, + client_id, + ServiceAccountChange::AddPermission(permission), + ) + .await + } + + /// Removes a permission from the client's service account. + pub async fn remove_permission_from_service_account( + &self, + caller: &Caller, + client_id: &TypedUuid, + permission: &T, + ) -> ResourceResult, OAuthError> { + self.modify_service_account( + caller, + client_id, + ServiceAccountChange::RemovePermission(permission), + ) + .await + } + + /// Applies a change to the permissions of a client's service account. + async fn modify_service_account( + &self, + caller: &Caller, + client_id: &TypedUuid, + change: ServiceAccountChange<'_, T>, + ) -> ResourceResult, OAuthError> { + if !Self::can_make_change(caller, client_id, &change) { + resource_restricted() + } else { + let client = self.get_oauth_client(caller, client_id).await?; + let current = ServiceAccountStore::get(&*self.storage, &client.id).await?; + + let mut update = NewServiceAccount { + id: client.id, + permissions: current + .as_ref() + .map(|account| account.permissions.expand_values()) + .unwrap_or_default(), + }; + Self::apply_change(&mut update, change); + update.permissions = ::contract(&update.permissions); + + let written = match current { + Some(account) => { + ServiceAccountStore::update(&*self.storage, update, account.generation).await? + } + None => ServiceAccountStore::create(&*self.storage, update) + .await + .map(Some) + .or_else(|err| match err { + StoreError::Conflict => Ok(None), + err => Err(err), + })?, + }; + + match written { + Some(account) => Ok(account.permissions), + None => { + tracing::info!( + ?client_id, + "Service account was written by someone else since it was read" + ); + resource_conflict() + } + } + } + } + + /// Returns true if the caller has the authority to make the change to the client's service + /// account + fn can_make_change( + caller: &Caller, + client_id: &TypedUuid, + change: &ServiceAccountChange, + ) -> bool { + let permission = match change { + ServiceAccountChange::AddPermission(permission) => permission, + ServiceAccountChange::RemovePermission(permission) => *permission, + }; + + caller.can(&VPermission::ManageOAuthClient(*client_id).into()) + && caller.can_grant(permission) + } + + fn apply_change(update: &mut NewServiceAccount, change: ServiceAccountChange) { + match change { + ServiceAccountChange::AddPermission(permission) => { + for value in Permissions::from_iter([permission]) + .expand_values() + .into_iter() + { + update.permissions.insert(value); + } + } + ServiceAccountChange::RemovePermission(permission) => { + update.permissions = update.permissions.without(permission); + } + } + } + pub async fn add_oauth_secret( &self, caller: &Caller, @@ -99,12 +582,14 @@ where client_id: &TypedUuid, secret: &str, ) -> ResourceResult { - if caller.can(&VPermission::ManageOAuthClient(*client_id).into()) { + let client = self.get_oauth_client(caller, client_id).await?; + + if caller.can(&VPermission::ManageOAuthClient(client.id).into()) { Ok(OAuthClientSecretStore::upsert( &*self.storage, NewOAuthClientSecret { id: *id, - oauth_client_id: *client_id, + oauth_client_id: client.id, secret_signature: secret.to_string(), }, ) @@ -147,13 +632,14 @@ where // include a fragment component. let redirect_url = parse_redirect_url(uri) .map_err(|e| ResourceError::InternalError(OAuthError::RedirectUri(e)))?; + let client = self.get_oauth_client(caller, client_id).await?; - if caller.can(&VPermission::ManageOAuthClient(*client_id).into()) { + if caller.can(&VPermission::ManageOAuthClient(client.id).into()) { Ok(OAuthClientRedirectUriStore::upsert( &*self.storage, NewOAuthClientRedirectUri { id: TypedUuid::new_v4(), - oauth_client_id: *client_id, + oauth_client_id: client.id, redirect_uri: redirect_url.to_string(), }, ) @@ -194,7 +680,7 @@ mod tests { use newtype_uuid::TypedUuid; use v_model::{ OAuthClient, OAuthClientRedirectUri, OAuthClientSecret, - permissions::Caller, + permissions::{Caller, Principal}, storage::{ MockOAuthClientRedirectUriStore, MockOAuthClientSecretStore, MockOAuthClientStore, }, @@ -229,6 +715,7 @@ mod tests { client_store.expect_get().returning(move |id, _| { Ok(Some(OAuthClient { id: *id, + keys: vec![], secrets: vec![], redirect_uris: vec![], created_at: Utc::now(), @@ -243,7 +730,7 @@ mod tests { // Attacker only manages their own client C. let attacker = Caller { - id: TypedUuid::new_v4(), + principal: Principal::User(TypedUuid::new_v4()), permissions: vec![VPermission::ManageOAuthClient(attacker_client_id)].into(), extensions: HashMap::default(), }; @@ -284,6 +771,7 @@ mod tests { client_store.expect_get().returning(move |id, _| { Ok(Some(OAuthClient { id: *id, + keys: vec![], secrets: vec![], redirect_uris: vec![], created_at: Utc::now(), @@ -297,7 +785,7 @@ mod tests { let ctx = OAuthContext::new(Arc::new(storage)); let attacker = Caller { - id: TypedUuid::new_v4(), + principal: Principal::User(TypedUuid::new_v4()), permissions: vec![VPermission::ManageOAuthClient(attacker_client_id)].into(), extensions: HashMap::default(), }; diff --git a/v-api/src/context/user.rs b/v-api/src/context/user.rs index 13ce81a9..0486f858 100644 --- a/v-api/src/context/user.rs +++ b/v-api/src/context/user.rs @@ -13,7 +13,7 @@ use v_model::{ AccessGroup, AccessToken, ApiKey, ApiKeyId, ApiUser, ApiUserContactEmail, ApiUserInfo, ApiUserProvider, ArcMap, NewAccessToken, NewApiKey, NewApiUser, NewApiUserContactEmail, NewApiUserProvider, Permissions, UserId, UserProviderId, - permissions::{AsScope, Caller, Permission, PermissionError, PermissionStorage}, + permissions::{AsScope, Caller, Permission, PermissionError, PermissionStorage, Principal}, storage::{ AccessGroupFilter, AccessGroupStore, AccessTokenStore, ApiKeyFilter, ApiKeyStore, ApiUserContactEmailStore, ApiUserFilter, ApiUserProviderFilter, ApiUserProviderStore, @@ -24,12 +24,13 @@ use v_model::{ use crate::{ VApiStorage, authn::{ - AuthToken, Verify, - jwt::{Claims, JwtSigner, JwtSignerError}, + UserToken, Verify, + jwt::{JwtSigner, JwtSignerError, UserClaims}, }, permissions::{VAppPermission, VPermission}, response::{ - OptionalResource, ResourceError, ResourceResult, resource_not_found, resource_restricted, + OptionalResource, ResourceError, ResourceResult, resource_conflict, resource_not_found, + resource_restricted, }, }; @@ -88,6 +89,15 @@ where } } +/// A change to the permissions or groups held directly by a user. Each kind of change carries +/// what is needed to check the caller's authority to make it. +enum UserChange<'a, T> { + AddPermissions { permissions: Permissions }, + RemovePermission { permission: &'a T }, + JoinGroup(&'a AccessGroup), + LeaveGroup(&'a AccessGroup), +} + #[derive(Clone)] pub struct UserContext { caller_extension_handlers: Vec>>, @@ -137,7 +147,7 @@ where &self, registration_user: &Caller, verifier: &U, - token: &AuthToken, + token: &UserToken, ) -> Result, UserContextError> where U: Verify, @@ -182,7 +192,7 @@ where BasePermissions::Restricted(permissions) => { let token_permissions = ::expand( permissions, - &info.user, + Some(&info.user), Some(&user_permissions), &extensions, ); @@ -193,12 +203,12 @@ where tracing::trace!(token = ?base_permissions, user = ?user_permissions, combined = ?combined_permissions, "Computed caller permissions"); let caller: Caller = Caller { - id: info.user.id, + principal: Principal::User(info.user.id), permissions: combined_permissions.into_iter().collect::>(), extensions, }; - tracing::info!(?caller.id, "Resolved caller"); + tracing::info!(?caller.principal, "Resolved caller"); tracing::debug!(?caller.permissions, "Caller permissions"); Ok(caller) @@ -208,13 +218,13 @@ where &self, caller: &Caller, verifier: &U, - auth: &AuthToken, + auth: &UserToken, ) -> Result<(TypedUuid, BasePermissions), UserContextError> where U: Verify, { match auth { - AuthToken::ApiKey(api_key) => { + UserToken::ApiKey(api_key) => { async { tracing::debug!("Attempt to authenticate"); @@ -266,8 +276,8 @@ where .instrument(info_span!("Test api key")) .await } - AuthToken::Jwt(jwt) => { - // AuthnToken::Jwt can only be generated from a verified JWT + UserToken::Session(jwt) => { + // AuthnToken::Session can only be generated from a verified JWT let permissions = if jwt.claims.scp.iter().any(|s| s == "full") { BasePermissions::Full } else { @@ -327,7 +337,7 @@ where let permissions = groups .into_iter() .fold(Permissions::new(), |mut aggregate, group| { - let mut expanded = ::expand(&group.permissions, user, Some(&user.permissions), extensions); + let mut expanded = ::expand(&group.permissions, Some(user), Some(&user.permissions), extensions); tracing::trace!(group_id = ?group.id, group_name = ?group.name, permissions = ?expanded, "Transformed group into permission set"); aggregate.append(&mut expanded); @@ -340,33 +350,41 @@ where // API User Operations - #[instrument(skip(self, caller), fields(caller = ?caller.id))] + #[instrument(skip(self, caller), fields(caller = ?caller.principal))] pub async fn get_api_user( &self, caller: &Caller, id: &TypedUuid, ) -> ResourceResult, StoreError> { - if caller.can(&VPermission::GetApiUser(*id).into()) { - let mut info = ApiUserStore::get(&*self.storage, id, false) - .await - .optional()?; + let mut info = self.get_stored_api_user(caller, id).await?; + let extensions = self.get_extensions(&info.user).await; - let extensions = self.get_extensions(&info.user).await; + info.user.permissions = ::expand( + &info.user.permissions, + Some(&info.user), + None, + &extensions, + ); - info.user.permissions = ::expand( - &info.user.permissions, - &info.user, - None, - &extensions, - ); + Ok(info) + } - Ok(info) + /// Reads a user as it is (notably without expanding permissions). + async fn get_stored_api_user( + &self, + caller: &Caller, + id: &TypedUuid, + ) -> ResourceResult, StoreError> { + if caller.can(&VPermission::GetApiUser(*id).into()) { + ApiUserStore::get(&*self.storage, id, false) + .await + .optional() } else { resource_restricted() } } - #[instrument(skip(self, caller, filter, pagination), fields(caller = ?caller.id))] + #[instrument(skip(self, caller, filter, pagination), fields(caller = ?caller.principal))] pub async fn list_api_user( &self, caller: &Caller, @@ -380,7 +398,7 @@ where Ok(users) } - #[instrument(skip(self, caller), fields(caller = ?caller.id))] + #[instrument(skip(self, caller), fields(caller = ?caller.principal))] pub async fn create_api_user( &self, caller: &Caller, @@ -393,121 +411,203 @@ where .flat_map(|g| g.permissions.iter().cloned()) .collect(); - if caller.can(&VPermission::CreateApiUser.into()) - && caller.can_grant_all(&permissions) + if caller.all( + [ + VPermission::CreateApiUser.into(), + VPermission::ManageGroupMembershipsAll.into(), + ] + .iter(), + ) && caller.can_grant_all(&permissions) && caller.can_grant_all(&group_permissions) { - let new_user = NewApiUser { + let mut new_user = NewApiUser { id, permissions, groups: groups.into_iter().map(|g| g.id).collect(), }; - self.save_api_user(new_user).await - } else { - resource_restricted() - } - } - /// Replaces the direct permissions on a user. Group membership is not affected. - /// The caller must hold every permission that is being newly added. - #[instrument(skip(self, caller, user_id, permissions), fields(caller = ?caller.id))] - pub async fn set_api_user_permissions( - &self, - caller: &Caller, - user_id: &TypedUuid, - permissions: Permissions, - ) -> ResourceResult, StoreError> { - if caller.can(&VPermission::ManageApiUser(*user_id).into()) - && caller.can_grant_all(&permissions) - { - let info = self.get_api_user(caller, user_id).await?; - let mut update: NewApiUser = info.user.into(); - update.permissions = permissions; - self.save_api_user(update).await + new_user.permissions = ::contract(&new_user.permissions); + Ok(ApiUserStore::create(&*self.storage, new_user).await?) } else { resource_restricted() } } - #[instrument(skip(self, caller, user_id, new_permissions), fields(caller = ?caller.id))] + /// Adds permissions directly to a user. The caller must be able to manage the user's + /// permissions and grant every new permission for any permissions to be added. + #[instrument(skip(self, caller, user_id, new_permissions), fields(caller = ?caller.principal))] pub async fn add_permissions_to_user( &self, caller: &Caller, user_id: &TypedUuid, new_permissions: Permissions, ) -> ResourceResult, StoreError> { - if caller.can(&VPermission::ManageApiUser(*user_id).into()) - && caller.can_grant_all(&new_permissions) - { - let info = self.get_api_user(caller, user_id).await?; - - let mut user_update: NewApiUser = info.user.into(); - for permission in new_permissions.into_iter() { - tracing::info!(id = ?user_id, ?permission, "Adding permission to user"); - user_update.permissions.insert(permission); - } - - self.save_api_user(user_update).await - } else { - resource_restricted() - } + self.modify_api_user( + caller, + user_id, + UserChange::AddPermissions { + permissions: new_permissions, + }, + ) + .await } - /// Adds a single permission to a user. The caller must hold the permission being added. - #[instrument(skip(self, caller, user_id, permission), fields(caller = ?caller.id))] + /// Adds a permission directly to a user. The caller must be able to manage the user's + /// permissions and grant the permission. + #[instrument(skip(self, caller, user_id, permission), fields(caller = ?caller.principal))] pub async fn add_permission_to_user( &self, caller: &Caller, user_id: &TypedUuid, permission: T, ) -> ResourceResult, StoreError> { - if caller.can(&VPermission::ManageApiUser(*user_id).into()) && caller.can_grant(&permission) - { - let info = self.get_api_user(caller, user_id).await?; - - let mut user_update: NewApiUser = info.user.into(); - tracing::info!(id = ?user_id, ?permission, "Adding permission to user"); - user_update.permissions.insert(permission); - - self.save_api_user(user_update).await - } else { - resource_restricted() - } + self.modify_api_user( + caller, + user_id, + UserChange::AddPermissions { + permissions: Permissions::from_iter([permission]), + }, + ) + .await } - /// Removes a single permission from a user. The caller does not need to hold the - /// permission being removed, only the ability to manage the target user. - #[instrument(skip(self, caller, user_id, permission), fields(caller = ?caller.id))] + /// Removes a permission held directly by a user. This does not affect permissions + /// attributed through group memberships. + #[instrument(skip(self, caller, user_id, permission), fields(caller = ?caller.principal))] pub async fn remove_permission_from_user( &self, caller: &Caller, user_id: &TypedUuid, permission: &T, ) -> ResourceResult, StoreError> { - if caller.can(&VPermission::ManageApiUser(*user_id).into()) { - let info = self.get_api_user(caller, user_id).await?; + self.modify_api_user(caller, user_id, UserChange::RemovePermission { permission }) + .await + } - let mut user_update: NewApiUser = info.user.into(); - tracing::info!(id = ?user_id, ?permission, "Removing permission from user"); - user_update.permissions.remove(permission); + /// Adds a user to a group. + pub async fn add_user_to_group( + &self, + caller: &Caller, + user_id: &TypedUuid, + group: &AccessGroup, + ) -> ResourceResult, StoreError> { + self.modify_api_user(caller, user_id, UserChange::JoinGroup(group)) + .await + } - self.save_api_user(user_update).await + /// Removes a user from a group. + pub async fn remove_user_from_group( + &self, + caller: &Caller, + user_id: &TypedUuid, + group: &AccessGroup, + ) -> ResourceResult, StoreError> { + self.modify_api_user(caller, user_id, UserChange::LeaveGroup(group)) + .await + } + + /// Applies a change to a user's permissions and groups. + async fn modify_api_user( + &self, + caller: &Caller, + user_id: &TypedUuid, + change: UserChange<'_, T>, + ) -> ResourceResult, StoreError> { + if Self::can_make_change(caller, user_id, &change) { + let current = self.get_stored_api_user(caller, user_id).await?; + let read_generation = current.user.generation; + + let mut update: NewApiUser = current.user.into(); + update.permissions = update.permissions.expand_values(); + Self::apply_change(&mut update, change); + update.permissions = ::contract(&update.permissions); + + match ApiUserStore::update(&*self.storage, update, read_generation).await? { + Some(updated) => Ok(updated), + None => { + tracing::info!( + ?user_id, + generation = read_generation, + "User was written by someone else since it was read" + ); + resource_conflict() + } + } } else { resource_restricted() } } - /// Contracts permissions and persists the user. Callers are responsible for performing - /// any authorization and escalation checks before calling this method. - async fn save_api_user( - &self, - mut api_user: NewApiUser, - ) -> ResourceResult, StoreError> { - api_user.permissions = ::contract(&api_user.permissions); - Ok(ApiUserStore::upsert(&*self.storage, api_user).await?) + fn apply_change(update: &mut NewApiUser, change: UserChange) { + match change { + UserChange::AddPermissions { permissions, .. } => { + for permission in permissions.expand_values().into_iter() { + tracing::info!(id = ?update.id, ?permission, "Adding permission to user"); + update.permissions.insert(permission); + } + } + UserChange::RemovePermission { permission, .. } => { + tracing::info!(id = ?update.id, ?permission, "Removing permission from user"); + update.permissions = update.permissions.without(permission); + } + UserChange::JoinGroup(group) => { + update.groups.insert(group.id); + } + UserChange::LeaveGroup(group) => { + update.groups.retain(|id| id != &group.id); + } + } + } + + /// Returns true if the caller can make this change to the user + fn can_make_change( + caller: &Caller, + user_id: &TypedUuid, + change: &UserChange, + ) -> bool { + match change { + UserChange::AddPermissions { permissions } => { + Self::can_manage_permissions(caller, user_id) && caller.can_grant_all(permissions) + } + UserChange::RemovePermission { permission } => { + Self::can_manage_permissions(caller, user_id) && caller.can_grant(permission) + } + UserChange::JoinGroup(group) => Self::can_change_membership(caller, group, "add"), + UserChange::LeaveGroup(group) => Self::can_change_membership(caller, group, "remove"), + } + } + + /// Returns true if the caller can change the permissions directly assigned to the user. + fn can_manage_permissions(caller: &Caller, user_id: &TypedUuid) -> bool { + caller.can(&VPermission::ManageApiUser(*user_id).into()) + } + + // TODO: This is evidence of a problem in our data model. Storing groups on the user model means + // that we have to modify a user to assign a group. But what we actually care about are group + // permissions. This is for a future larger refactoring of the data model. + + /// Returns true if the caller may add users to or remove users from the group. + fn can_change_membership(caller: &Caller, group: &AccessGroup, action: &str) -> bool { + let can_manage_membership = + caller.can(&VPermission::ManageGroupMembership(group.id).into()); + let can_grant_permissions = caller.can_grant_all(&group.permissions); + + if !can_manage_membership || !can_grant_permissions { + tracing::warn!( + caller = ?caller.principal, + group_id = ?group.id, + group_name = ?group.name, + action, + can_manage_membership, + can_grant_permissions, + "Caller is not permitted to change membership of group" + ); + } + + can_manage_membership && can_grant_permissions } - #[instrument(skip(self, caller, token, api_user_id), fields(caller = ?caller.id))] + #[instrument(skip(self, caller, token, api_user_id), fields(caller = ?caller.principal))] pub async fn create_api_user_token( &self, caller: &Caller, @@ -518,7 +618,7 @@ where // If the user is requesting a token for themselves, they can grant an unbounded token. // If the request is for a different user, then a permission boundary must be provided. - let self_token = &caller.id == api_user_id; + let self_token = caller.is(api_user_id); let has_boundary = token.permission_boundary.is_some(); let can_grant = token .permission_boundary @@ -676,7 +776,7 @@ where caller: &Caller, signer: &JwtSigner, api_user: &TypedUuid, - claims: &Claims, + claims: &UserClaims, ) -> ResourceResult { let token = self .create_access_token( @@ -726,7 +826,7 @@ mod tests { use newtype_uuid::TypedUuid; use v_model::{ ApiKey, NewApiKey, UserId, - permissions::{Caller, Permissions}, + permissions::{Caller, Permissions, Principal}, storage::MockApiKeyStore, }; @@ -759,7 +859,7 @@ mod tests { fn make_caller(id: TypedUuid, permissions: Vec) -> Caller { Caller { - id, + principal: Principal::User(id), permissions: permissions.into(), extensions: HashMap::default(), } diff --git a/v-api/src/endpoints/api_user.rs b/v-api/src/endpoints/api_user.rs index 0f16ca99..9c196aef 100644 --- a/v-api/src/endpoints/api_user.rs +++ b/v-api/src/endpoints/api_user.rs @@ -2,12 +2,12 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use std::collections::{BTreeSet, HashMap, hash_map::Entry}; +use std::collections::{HashMap, hash_map::Entry}; use chrono::{DateTime, Utc}; use dropshot::{ HttpError, HttpResponseCreated, HttpResponseOk, HttpResponseUpdatedNoContent, Path, - RequestContext, TypedBody, + RequestContext, }; use newtype_uuid::{GenericUuid, TypedUuid}; use partial_struct::partial; @@ -19,7 +19,7 @@ use uuid::Uuid; use v_model::{ AccessGroupId, ApiKeyId, ApiUser, ApiUserContactEmail, ApiUserProvider, NewApiKey, UserId, permissions::{Caller, Permission, PermissionStorage, Permissions}, - storage::{AccessGroupFilter, ApiUserFilter, ApiUserProviderFilter, ListPagination}, + storage::{ApiUserFilter, ApiUserProviderFilter, ListPagination}, }; use crate::{ @@ -29,7 +29,7 @@ use crate::{ error::ApiError, permissions::{VAppPermission, VAppPermissionResponse}, secrets::OpenApiSecretString, - util::response::{bad_request, not_found, to_internal_error, unauthorized}, + util::response::{bad_request, forbidden, not_found, to_internal_error, unauthorized}, }; fn into_user_response(user: ApiUser) -> ApiUser @@ -48,6 +48,7 @@ where created_at: user.created_at, updated_at: user.updated_at, deleted_at: user.deleted_at, + generation: user.generation, } } @@ -83,7 +84,10 @@ where U: VAppPermissionResponse + From + JsonSchema, { let (ctx, caller) = rqctx.as_ctx().await?; - let info = ctx.user.get_api_user(&caller, &caller.id).await?; + + // Only a user has a user record to describe + let user_id = caller.user_id().ok_or_else(forbidden)?; + let info = ctx.user.get_api_user(&caller, &user_id).await?; let filter = ApiUserProviderFilter { api_user_id: Some(vec![info.user.id]), @@ -189,124 +193,11 @@ where Ok(HttpResponseOk(responses)) } -#[derive(Debug, Clone, PartialEq, Deserialize, JsonSchema)] -pub struct ApiUserUpdateParams { - permissions: Permissions, - #[serde(default)] - group_ids: BTreeSet>, -} - -/// Creates a new API user with the specified permissions and group memberships. -/// -/// Returns the newly created user's information along with any associated providers. -#[instrument(skip(rqctx), err(Debug))] -pub async fn create_api_user_op( - rqctx: &RequestContext>, - body: TypedBody>, -) -> Result>, HttpError> -where - T: VAppPermission + JsonSchema + PermissionStorage, - U: VAppPermissionResponse + From + JsonSchema, -{ - let (ctx, caller) = rqctx.as_ctx().await?; - let body = body.into_inner(); - - create_api_user_inner(ctx, caller, body).await -} - -#[instrument(skip(ctx, body))] -pub async fn create_api_user_inner( - ctx: &VContext, - caller: Caller, - body: ApiUserUpdateParams, -) -> Result>, HttpError> -where - T: VAppPermission + JsonSchema + PermissionStorage, - U: VAppPermissionResponse + From + JsonSchema, -{ - // Resolve the full groups so that create_api_user can verify the caller - // is allowed to grant the permissions they carry. - let groups = ctx - .group - .list_groups( - &caller, - AccessGroupFilter { - id: Some(body.group_ids.into_iter().collect()), - ..Default::default() - }, - ) - .await?; - - let info = ctx - .user - .create_api_user(&caller, TypedUuid::new_v4(), body.permissions, groups) - .await?; - - let filter = ApiUserProviderFilter { - api_user_id: Some(vec![info.user.id]), - ..Default::default() - }; - let providers = ctx - .user - .list_api_user_provider(&caller, filter, &ListPagination::default().limit(10)) - .await?; - - Ok(HttpResponseCreated(GetUserResponse::new( - info.user, providers, - ))) -} - #[derive(Clone, Debug, Deserialize, JsonSchema)] pub struct ApiUserPath { user_id: TypedUuid, } -/// Updates an existing API user's direct permissions. Group membership is managed -/// separately via the group membership endpoints. -/// -/// Returns the updated user's information along with their associated providers. -#[instrument(skip(rqctx), err(Debug))] -pub async fn update_api_user_op( - rqctx: &RequestContext>, - path: ApiUserPath, - body: ApiUserUpdateParams, -) -> Result>, HttpError> -where - T: VAppPermission + PermissionStorage, - U: VAppPermissionResponse + From + JsonSchema, -{ - let (ctx, caller) = rqctx.as_ctx().await?; - update_api_user_inner(ctx, caller, path, body).await -} - -#[instrument(skip(ctx, body))] -pub async fn update_api_user_inner( - ctx: &VContext, - caller: Caller, - path: ApiUserPath, - body: ApiUserUpdateParams, -) -> Result>, HttpError> -where - T: VAppPermission + PermissionStorage, - U: VAppPermissionResponse + From + JsonSchema, -{ - let info = ctx - .user - .set_api_user_permissions(&caller, &path.user_id, body.permissions) - .await?; - - let filter = ApiUserProviderFilter { - api_user_id: Some(vec![info.user.id]), - ..Default::default() - }; - let providers = ctx - .user - .list_api_user_provider(&caller, filter, &ListPagination::default().limit(10)) - .await?; - - Ok(HttpResponseOk(GetUserResponse::new(info.user, providers))) -} - /// Lists all API tokens for a specific user. /// /// Returns a collection of API tokens associated with the specified user, @@ -795,7 +686,7 @@ where // // This endpoint can only be called by the user themselves, it can not be performed on behalf // of a user - if path.user_id == caller.id { + if caller.is(&path.user_id) { let secret = RawKey::try_from(body.token.as_str()).map_err(|err| { tracing::debug!(?err, "Invalid link request token"); bad_request("Malformed link request token") @@ -818,7 +709,7 @@ where // Verify that the found link request is assigned to the user calling the endpoint and that // the token provided matches the stored signature - if link_request.target_user_id == caller.id + if caller.is(&link_request.target_user_id) && secret .verify(ctx, link_request.secret_signature.as_bytes()) .is_ok() @@ -868,7 +759,7 @@ where mod tests { use std::{ collections::{BTreeSet, HashMap}, - sync::Arc, + sync::{Arc, Mutex}, }; use chrono::{TimeDelta, Utc}; @@ -876,28 +767,26 @@ mod tests { use mockall::predicate::eq; use newtype_uuid::TypedUuid; use v_model::{ - ApiKey, ApiUser, ApiUserContactEmail, ApiUserInfo, ApiUserProvider, NewApiUser, - permissions::{Caller, Permissions}, + ApiKey, ApiUser, ApiUserContactEmail, ApiUserInfo, ApiUserProvider, UserId, + permissions::{Caller, PermissionStorage, Permissions, Principal}, storage::{ - ApiKeyFilter, ListPagination, MockAccessGroupStore, MockApiKeyStore, - MockApiUserContactEmailStore, MockApiUserProviderStore, MockApiUserStore, StoreError, + ApiKeyFilter, ListPagination, MockApiKeyStore, MockApiUserContactEmailStore, + MockApiUserProviderStore, MockApiUserStore, MockOAuthClientStore, StoreError, }, }; use crate::{ context::test_mocks::{MockStorage, mock_context}, endpoints::api_user::{ - ApiKeyCreateParams, ApiUserEmailUpdateParams, ApiUserPath, ApiUserTokenPath, - create_api_user_inner, create_api_user_token_inner, delete_api_user_token_inner, - get_api_user_token_inner, list_api_user_tokens_inner, set_api_user_contact_email_inner, - update_api_user_inner, + ApiKeyCreateParams, ApiUserEmailUpdateParams, ApiUserPath, ApiUserPermissionParams, + ApiUserTokenPath, add_api_user_permission_inner, create_api_user_token_inner, + delete_api_user_token_inner, get_api_user_token_inner, list_api_user_tokens_inner, + remove_api_user_permission_inner, set_api_user_contact_email_inner, }, permissions::{VPermission, VPermissionResponse}, util::tests::get_status, }; - use super::ApiUserUpdateParams; - fn mock_user() -> ApiUser { ApiUser { id: TypedUuid::new_v4(), @@ -906,260 +795,10 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, } } - #[tokio::test] - async fn test_create_api_user_permissions() { - let successful_update = ApiUserUpdateParams { - permissions: vec![VPermission::CreateApiUser].into(), - group_ids: BTreeSet::new(), - }; - - let failure_update = ApiUserUpdateParams { - permissions: vec![VPermission::GetApiUsersAll].into(), - group_ids: BTreeSet::new(), - }; - - let mut store = MockApiUserStore::new(); - store - .expect_upsert() - .withf(|x: &NewApiUser| x.permissions.can(&VPermission::CreateApiUser)) - .returning(|user| { - Ok(ApiUserInfo { - user: ApiUser { - id: user.id, - permissions: user.permissions, - groups: BTreeSet::new(), - created_at: Utc::now(), - updated_at: Utc::now(), - deleted_at: None, - }, - email: None, - providers: vec![], - }) - }); - store - .expect_upsert() - .withf(|x: &NewApiUser| x.permissions.can(&VPermission::GetApiUsersAll)) - .returning(|_| Err(StoreError::Unknown)); - let mut api_user_provider_store = MockApiUserProviderStore::new(); - api_user_provider_store - .expect_list() - .returning(|_, _| Ok(vec![])); - - let mut access_group_store = MockAccessGroupStore::new(); - access_group_store - .expect_list() - .returning(|_, _| Ok(vec![])); - - let mut storage = MockStorage::new(); - storage.api_user_store = Some(Arc::new(store)); - storage.api_user_provider_store = Some(Arc::new(api_user_provider_store)); - storage.access_group_store = Some(Arc::new(access_group_store)); - - let ctx = mock_context(Arc::new(storage)).await; - - let user1 = mock_user(); - - // 1. Fail to create due to lack of permissions - let no_permissions = Caller { - id: user1.id, - permissions: Permissions::new(), - extensions: HashMap::default(), - }; - - let resp = create_api_user_inner::( - &ctx, - no_permissions, - successful_update.clone(), - ) - .await; - - assert!(resp.is_err()); - assert_eq!(get_status(&resp), StatusCode::FORBIDDEN); - - let user2 = mock_user(); - - // 2. Succeed in creating new api user - let with_permissions = Caller { - id: user2.id, - permissions: vec![VPermission::CreateApiUser].into(), - extensions: HashMap::default(), - }; - - let resp = create_api_user_inner::( - &ctx, - with_permissions.clone(), - successful_update.clone(), - ) - .await; - - assert!(resp.is_ok()); - assert_eq!(get_status(&resp), StatusCode::CREATED); - - // 3. Handle storage failure and return error - let resp = create_api_user_inner::( - &ctx, - with_permissions, - failure_update.clone(), - ) - .await; - - assert!(resp.is_err()); - assert_eq!(get_status(&resp), StatusCode::FORBIDDEN); - } - - #[tokio::test] - async fn test_update_api_user_permissions() { - let success_id = TypedUuid::new_v4(); - let successful_update = ApiUserUpdateParams { - permissions: Permissions::new(), - group_ids: BTreeSet::new(), - }; - - let failure_id = TypedUuid::new_v4(); - let failure_update = ApiUserUpdateParams { - permissions: Permissions::new(), - group_ids: BTreeSet::new(), - }; - - let mut store = MockApiUserStore::new(); - store.expect_get().returning(|id, _| { - Ok(Some(ApiUserInfo { - user: ApiUser { - id: *id, - permissions: Permissions::new(), - groups: BTreeSet::new(), - created_at: Utc::now(), - updated_at: Utc::now(), - deleted_at: None, - }, - email: None, - providers: vec![], - })) - }); - store - .expect_upsert() - .withf(move |x: &NewApiUser| x.id == success_id) - .returning(|user| { - Ok(ApiUserInfo { - user: ApiUser { - id: user.id, - permissions: user.permissions, - groups: BTreeSet::new(), - created_at: Utc::now(), - updated_at: Utc::now(), - deleted_at: None, - }, - email: None, - providers: vec![], - }) - }); - store - .expect_upsert() - .withf(move |x: &NewApiUser| x.id == failure_id) - .returning(|_| Err(StoreError::Unknown)); - let mut api_user_provider_store = MockApiUserProviderStore::new(); - api_user_provider_store - .expect_list() - .returning(|_, _| Ok(vec![])); - let mut access_group_store = MockAccessGroupStore::new(); - access_group_store - .expect_list() - .returning(|_, _| Ok(vec![])); - - let mut storage = MockStorage::new(); - storage.api_user_store = Some(Arc::new(store)); - storage.api_user_provider_store = Some(Arc::new(api_user_provider_store)); - storage.access_group_store = Some(Arc::new(access_group_store)); - - let ctx = mock_context(Arc::new(storage)).await; - - let success_path = ApiUserPath { - user_id: success_id, - }; - let failure_path = ApiUserPath { - user_id: failure_id, - }; - - let user1 = mock_user(); - - // 1. Fail to create due to lack of permissions - let no_permissions = Caller { - id: user1.id, - permissions: Permissions::new(), - extensions: HashMap::default(), - }; - - let resp = update_api_user_inner::( - &ctx, - no_permissions, - success_path.clone(), - successful_update.clone(), - ) - .await; - - assert!(resp.is_err()); - assert_eq!(get_status(&resp), StatusCode::FORBIDDEN); - - let user2 = mock_user(); - - // 2. Succeed in updating api user with direct permission - let with_specific_permissions = Caller { - id: user2.id, - permissions: vec![ - VPermission::GetApiUser(success_path.user_id), - VPermission::ManageApiUser(success_path.user_id), - ] - .into(), - extensions: HashMap::default(), - }; - - let resp = update_api_user_inner::( - &ctx, - with_specific_permissions, - success_path.clone(), - successful_update.clone(), - ) - .await; - - assert!(resp.is_ok()); - assert_eq!(get_status(&resp), StatusCode::OK); - - let user3 = mock_user(); - - // 3. Succeed in updating api user with general permission - let with_general_permissions = Caller { - id: user3.id, - permissions: vec![VPermission::GetApiUsersAll, VPermission::ManageApiUsersAll].into(), - extensions: HashMap::default(), - }; - - let resp = update_api_user_inner::( - &ctx, - with_general_permissions.clone(), - success_path, - successful_update.clone(), - ) - .await; - - assert!(resp.is_ok()); - assert_eq!(get_status(&resp), StatusCode::OK); - - // 4. Handle storage failure and return error - let resp = update_api_user_inner::( - &ctx, - with_general_permissions, - failure_path, - failure_update.clone(), - ) - .await; - - assert!(resp.is_err()); - assert_eq!(get_status(&resp), StatusCode::INTERNAL_SERVER_ERROR); - } - #[tokio::test] async fn test_list_api_user_token_permissions() { let success_id = TypedUuid::new_v4(); @@ -1194,7 +833,7 @@ mod tests { // 1. Fail to list due to lack of permissions let no_permissions = Caller { - id: user1.id, + principal: Principal::User(user1.id), permissions: Permissions::new(), extensions: HashMap::default(), }; @@ -1215,7 +854,7 @@ mod tests { // 2. Fail to list due to incorrect permissions let incorrect_permissions = Caller { - id: user2.id, + principal: Principal::User(user2.id), permissions: vec![VPermission::GetApiKey(TypedUuid::new_v4())].into(), extensions: HashMap::default(), }; @@ -1236,7 +875,7 @@ mod tests { // 3. Succeed in list tokens let success_permissions = Caller { - id: user3.id, + principal: Principal::User(user3.id), permissions: vec![VPermission::GetApiKey(TypedUuid::new_v4())].into(), extensions: HashMap::default(), }; @@ -1257,7 +896,7 @@ mod tests { // 4. Handle storage failure and return error let failure_permissions = Caller { - id: user4.id, + principal: Principal::User(user4.id), permissions: vec![VPermission::GetApiKey(TypedUuid::new_v4())].into(), extensions: HashMap::default(), }; @@ -1287,6 +926,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }; let api_user_path = ApiUserPath { @@ -1345,6 +985,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }, email: None, providers: vec![], @@ -1383,7 +1024,7 @@ mod tests { // 1. Fail to create due to lack of permissions let no_permissions = Caller { - id: user1.id, + principal: Principal::User(user1.id), permissions: Permissions::new(), extensions: HashMap::default(), }; @@ -1403,7 +1044,7 @@ mod tests { // 2. Fail to create due to incorrect permissions let incorrect_permissions = Caller { - id: user2.id, + principal: Principal::User(user2.id), permissions: vec![VPermission::CreateApiKey(TypedUuid::new_v4())].into(), extensions: HashMap::default(), }; @@ -1423,7 +1064,7 @@ mod tests { // 3. Fail to create due to unknown user let incorrect_permissions = Caller { - id: user3.id, + principal: Principal::User(user3.id), permissions: vec![ VPermission::GetApiUser(unknown_api_user_path.user_id), VPermission::CreateApiKey(unknown_api_user_path.user_id), @@ -1445,7 +1086,7 @@ mod tests { // 4. Succeed in creating token let success_permissions = Caller { - id: allowed_user_path.user_id, + principal: Principal::User(allowed_user_path.user_id), permissions: vec![ VPermission::GetApiUser(allowed_user_path.user_id), VPermission::CreateApiKey(allowed_user_path.user_id), @@ -1473,7 +1114,7 @@ mod tests { // 5. Handle storage failure and return error let failure_permissions = Caller { - id: user5.id, + principal: Principal::User(user5.id), permissions: vec![ VPermission::GetApiUser(failure_api_user_path.user_id), VPermission::CreateApiKey(failure_api_user_path.user_id), @@ -1547,7 +1188,7 @@ mod tests { // 1. Fail to get due to lack of permissions let no_permissions = Caller { - id: user1.id, + principal: Principal::User(user1.id), permissions: Permissions::new(), extensions: HashMap::default(), }; @@ -1566,7 +1207,7 @@ mod tests { // 2. Fail to get due to incorrect permissions let incorrect_permissions = Caller { - id: user2.id, + principal: Principal::User(user2.id), permissions: vec![VPermission::GetApiKey(TypedUuid::new_v4())].into(), extensions: HashMap::default(), }; @@ -1585,7 +1226,7 @@ mod tests { // 3. Fail to get due to unknown token id let incorrect_permissions = Caller { - id: user3.id, + principal: Principal::User(user3.id), permissions: vec![VPermission::GetApiKey( unknown_api_user_token_path.api_key_id, )] @@ -1607,7 +1248,7 @@ mod tests { // 4. Succeed in getting token let success_permissions = Caller { - id: user4.id, + principal: Principal::User(user4.id), permissions: vec![VPermission::GetApiKey(api_user_token_path.api_key_id)].into(), extensions: HashMap::default(), }; @@ -1626,7 +1267,7 @@ mod tests { // 5. Handle storage failure and return error let failure_permissions = Caller { - id: user5.id, + principal: Principal::User(user5.id), permissions: vec![VPermission::GetApiKey( failure_api_user_token_path.api_key_id, )] @@ -1698,7 +1339,7 @@ mod tests { // 1. Fail to get due to lack of permissions let no_permissions = Caller { - id: user1.id, + principal: Principal::User(user1.id), permissions: Permissions::new(), extensions: HashMap::default(), }; @@ -1717,7 +1358,7 @@ mod tests { // 2. Fail to get due to incorrect permissions let incorrect_permissions = Caller { - id: user2.id, + principal: Principal::User(user2.id), permissions: vec![VPermission::ManageApiKey(TypedUuid::new_v4())].into(), extensions: HashMap::default(), }; @@ -1736,7 +1377,7 @@ mod tests { // 3. Fail to get due to unknown token id let incorrect_permissions = Caller { - id: user3.id, + principal: Principal::User(user3.id), permissions: vec![VPermission::ManageApiKey( unknown_api_user_token_path.api_key_id, )] @@ -1758,7 +1399,7 @@ mod tests { // 4. Succeed in getting token let success_permissions = Caller { - id: user4.id, + principal: Principal::User(user4.id), permissions: vec![VPermission::ManageApiKey(api_user_token_path.api_key_id)].into(), extensions: HashMap::default(), }; @@ -1777,7 +1418,7 @@ mod tests { // 5. Handle storage failure and return error let failure_permissions = Caller { - id: user5.id, + principal: Principal::User(user5.id), permissions: vec![VPermission::ManageApiKey( failure_api_user_token_path.api_key_id, )] @@ -1814,6 +1455,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }, email: None, providers: vec![ApiUserProvider { @@ -1852,7 +1494,7 @@ mod tests { // 1. Fail to update due to no access let no_permissions = Caller { - id: user.id, + principal: Principal::User(user.id), permissions: Permissions::new(), extensions: HashMap::default(), }; @@ -1871,7 +1513,7 @@ mod tests { // 2. Fail due to lack of write permission let no_write_permissions = Caller { - id: user.id, + principal: Principal::User(user.id), permissions: vec![VPermission::GetApiUser(user.id)].into(), extensions: HashMap::default(), }; @@ -1890,7 +1532,7 @@ mod tests { // 4. Fail to update to non-owned email let write_permission = Caller { - id: user.id, + principal: Principal::User(user.id), permissions: vec![VPermission::GetApiUser(user.id)].into(), extensions: HashMap::default(), }; @@ -1909,7 +1551,7 @@ mod tests { // 5. Succeed in creating email let write_permission = Caller { - id: user.id, + principal: Principal::User(user.id), permissions: vec![ VPermission::GetApiUser(user.id), VPermission::ManageApiUser(user.id), @@ -1931,4 +1573,200 @@ mod tests { assert_eq!(get_status(&resp), StatusCode::OK); assert_eq!("user@company".to_string(), resp.unwrap().0.email); } + + fn stored_user( + id: TypedUuid, + permissions: Permissions, + ) -> ApiUserInfo { + ApiUserInfo { + user: ApiUser { + id, + permissions, + groups: BTreeSet::new(), + created_at: Utc::now(), + updated_at: Utc::now(), + deleted_at: None, + generation: 0, + }, + email: None, + providers: vec![], + } + } + + fn caller_with(permissions: Vec) -> Caller { + Caller { + principal: Principal::User(TypedUuid::new_v4()), + permissions: permissions.into(), + extensions: HashMap::default(), + } + } + + /// The permissions written by each successful permission change + type Writes = Arc>>>; + + /// A context holding a single user. When `client` is set, that OAuth client is backed by the + /// user. Every write succeeds and is recorded. + async fn permission_ctx( + user: ApiUserInfo, + ) -> (crate::VContext, Writes) { + let writes: Writes = Arc::new(Mutex::new(vec![])); + + let mut user_store = MockApiUserStore::new(); + let current = user.clone(); + user_store + .expect_get() + .returning(move |_, _| Ok(Some(current.clone()))); + let recorder = writes.clone(); + user_store.expect_update().returning(move |update, _| { + recorder.lock().unwrap().push(update.permissions.clone()); + Ok(Some(stored_user(update.id, update.permissions))) + }); + + let mut provider_store = MockApiUserProviderStore::new(); + provider_store.expect_list().returning(|_, _| Ok(vec![])); + + let mut storage = MockStorage::new(); + storage.api_user_store = Some(Arc::new(user_store)); + storage.api_user_provider_store = Some(Arc::new(provider_store)); + + (mock_context(Arc::new(storage)).await, writes) + } + + /// Adding a permission requires managing the user and being able to grant the permission + #[tokio::test] + async fn test_add_api_user_permission_requires_grant() { + let user_id = TypedUuid::new_v4(); + let (ctx, writes) = permission_ctx(stored_user(user_id, Permissions::new())).await; + let body = || ApiUserPermissionParams { + permission: VPermission::CreateGroup, + }; + + let cannot_grant = caller_with(vec![VPermission::ManageApiUser(user_id)]); + let resp = add_api_user_permission_inner::( + &ctx, + cannot_grant, + ApiUserPath { user_id }, + body(), + ) + .await; + assert_eq!(get_status(&resp), StatusCode::FORBIDDEN); + + let cannot_manage = caller_with(vec![VPermission::CreateGroup]); + let resp = add_api_user_permission_inner::( + &ctx, + cannot_manage, + ApiUserPath { user_id }, + body(), + ) + .await; + assert_eq!(get_status(&resp), StatusCode::FORBIDDEN); + assert!(writes.lock().unwrap().is_empty()); + + let can_grant = caller_with(vec![ + VPermission::GetApiUser(user_id), + VPermission::ManageApiUser(user_id), + VPermission::CreateGroup, + ]); + let resp = add_api_user_permission_inner::( + &ctx, + can_grant, + ApiUserPath { user_id }, + body(), + ) + .await; + assert_eq!(get_status(&resp), StatusCode::OK); + assert!(writes.lock().unwrap()[0].can(&VPermission::CreateGroup)); + } + + /// Removing a permission requires being able to grant it, so a caller can never take away + /// permissions outside of their own authority. Removing one value of a stored set keeps the + /// rest of that set. + #[tokio::test] + async fn test_remove_api_user_permission_requires_grant() { + let user_id = TypedUuid::new_v4(); + let (a, b) = (TypedUuid::new_v4(), TypedUuid::new_v4()); + let user = stored_user( + user_id, + vec![VPermission::ManageGroups(BTreeSet::from([a, b]))].into(), + ); + let (ctx, writes) = permission_ctx(user).await; + let body = || ApiUserPermissionParams { + permission: VPermission::ManageGroup(a), + }; + + let cannot_grant = caller_with(vec![VPermission::ManageApiUser(user_id)]); + let resp = remove_api_user_permission_inner::( + &ctx, + cannot_grant, + ApiUserPath { user_id }, + body(), + ) + .await; + assert_eq!(get_status(&resp), StatusCode::FORBIDDEN); + assert!(writes.lock().unwrap().is_empty()); + + // Holding only `a` is enough to remove `a`, and leaves `b` with the user + let can_grant = caller_with(vec![ + VPermission::GetApiUser(user_id), + VPermission::ManageApiUser(user_id), + VPermission::ManageGroup(a), + ]); + let resp = remove_api_user_permission_inner::( + &ctx, + can_grant, + ApiUserPath { user_id }, + body(), + ) + .await; + assert_eq!(get_status(&resp), StatusCode::OK); + + let written = writes.lock().unwrap()[0].clone(); + assert!(!written.can(&VPermission::ManageGroup(a))); + assert!(written.can(&VPermission::ManageGroup(b))); + assert_eq!( + written, + VPermission::contract(&written), + "write was not contracted" + ); + } + + /// A write against a generation that has moved on is refused as a conflict after a single + /// attempt, and is never retried + #[tokio::test] + async fn test_permission_change_is_a_conflict_when_stale() { + let user_id = TypedUuid::new_v4(); + let mut user_store = MockApiUserStore::new(); + user_store + .expect_get() + .times(1) + .returning(move |_, _| Ok(Some(stored_user(user_id, Permissions::new())))); + user_store + .expect_update() + .times(1) + .returning(|_, _| Ok(None)); + + let mut client_store = MockOAuthClientStore::new(); + client_store.expect_list().returning(|_, _| Ok(vec![])); + + let mut storage = MockStorage::new(); + storage.api_user_store = Some(Arc::new(user_store)); + storage.oauth_client_store = Some(Arc::new(client_store)); + let ctx = mock_context(Arc::new(storage)).await; + + let caller = caller_with(vec![ + VPermission::GetApiUsersAll, + VPermission::ManageApiUsersAll, + VPermission::CreateGroup, + ]); + let resp = add_api_user_permission_inner::( + &ctx, + caller, + ApiUserPath { user_id }, + ApiUserPermissionParams { + permission: VPermission::CreateGroup, + }, + ) + .await; + assert_eq!(get_status(&resp), StatusCode::CONFLICT); + } } diff --git a/v-api/src/endpoints/api_user_provider.rs b/v-api/src/endpoints/api_user_provider.rs index dc78d889..3af35bdc 100644 --- a/v-api/src/endpoints/api_user_provider.rs +++ b/v-api/src/endpoints/api_user_provider.rs @@ -13,6 +13,7 @@ use crate::{ context::{ApiContext, VContextWithCaller}, permissions::VAppPermission, secrets::OpenApiSecretString, + util::response::forbidden, }; #[derive(Debug, Deserialize, JsonSchema)] @@ -44,20 +45,17 @@ where let path = path.into_inner(); let body = body.into_inner(); + // Login providers belong to users, so only a user can link one of theirs elsewhere + let user_id = caller.user_id().ok_or_else(forbidden)?; + let provider = ctx .user - .get_api_user_provider(&caller, &caller.id, &path.provider_id) + .get_api_user_provider(&caller, &user_id, &path.provider_id) .await?; let token = ctx .link - .create_link_request_token( - &caller, - ctx.signer(), - &provider.id, - &caller.id, - &body.user_id, - ) + .create_link_request_token(&caller, ctx.signer(), &provider.id, &user_id, &body.user_id) .await?; Ok(HttpResponseOk(ApiUserLinkRequestResponse { diff --git a/v-api/src/endpoints/group.rs b/v-api/src/endpoints/group.rs index 5c45f5c7..f9c0a5b8 100644 --- a/v-api/src/endpoints/group.rs +++ b/v-api/src/endpoints/group.rs @@ -39,6 +39,7 @@ where created_at: group.created_at, updated_at: group.updated_at, deleted_at: group.deleted_at, + generation: group.generation, } } @@ -97,11 +98,24 @@ pub struct AccessGroupPath { group_id: TypedUuid, } +#[derive(Debug, Clone, PartialEq, Deserialize, JsonSchema)] +pub struct AccessGroupPermissionParams { + permission: T, +} + +fn preset_group_error() -> HttpError { + client_error( + ClientErrorStatusCode::CONFLICT, + "Preset groups are managed via service configuration and cannot be modified at runtime", + ) +} + +/// Adds a single permission to a group. The caller must be able to grant it. #[instrument(skip(rqctx), err(Debug))] -pub async fn update_group_op( +pub async fn add_group_permission_op( rqctx: &RequestContext>, path: AccessGroupPath, - body: AccessGroupUpdateParams, + body: AccessGroupPermissionParams, ) -> Result>, HttpError> where T: VAppPermission + PermissionStorage, @@ -110,25 +124,40 @@ where let (ctx, caller) = rqctx.as_ctx().await?; if ctx.group.is_preset(&path.group_id) { - return Err(client_error( - ClientErrorStatusCode::CONFLICT, - "Preset groups are managed via service configuration and cannot be updated at runtime", - )); + Err(preset_group_error()) + } else { + Ok(HttpResponseOk( + ctx.group + .add_permission_to_group(&caller, &path.group_id, body.permission) + .await + .map(into_group_response)?, + )) } +} - Ok(HttpResponseOk( - ctx.group - .update_group( - &caller, - NewAccessGroup { - id: path.group_id, - name: body.name, - permissions: body.permissions, - }, - ) - .await - .map(into_group_response)?, - )) +/// Removes a single permission from a group. The caller must be able to grant it. +#[instrument(skip(rqctx), err(Debug))] +pub async fn remove_group_permission_op( + rqctx: &RequestContext>, + path: AccessGroupPath, + body: AccessGroupPermissionParams, +) -> Result>, HttpError> +where + T: VAppPermission + PermissionStorage, + U: From + Permission + JsonSchema, +{ + let (ctx, caller) = rqctx.as_ctx().await?; + + if ctx.group.is_preset(&path.group_id) { + Err(preset_group_error()) + } else { + Ok(HttpResponseOk( + ctx.group + .remove_permission_from_group(&caller, &path.group_id, &body.permission) + .await + .map(into_group_response)?, + )) + } } #[instrument(skip(rqctx), err(Debug))] diff --git a/v-api/src/endpoints/handlers.rs b/v-api/src/endpoints/handlers.rs index b0bf73d2..feb010ce 100644 --- a/v-api/src/endpoints/handlers.rs +++ b/v-api/src/endpoints/handlers.rs @@ -8,30 +8,32 @@ mod macros { macro_rules! v_system_endpoints { ($context_type:ident, $permission_type:ident) => { use dropshot::{ - endpoint, HttpError, HttpResponseCreated, HttpResponseOk, + endpoint, HttpError, HttpResponseCreated, HttpResponseHeaders, HttpResponseOk, HttpResponseTemporaryRedirect, HttpResponseUpdatedNoContent, Path, Query, RequestContext, TypedBody, Body, }; use http::Response; - use v_model::{Mapper, ApiUserContactEmail, OAuthClient, OAuthClientRedirectUri, OAuthClientSecret, AccessGroup, ApiUser, MagicLink, MagicLinkRedirectUri, MagicLinkSecret}; + use v_api::authn::client_key::SubmittedJwk; + use v_model::{Mapper, ApiUserContactEmail, OAuthClient, OAuthClientKey, OAuthClientRedirectUri, OAuthClientSecret, AccessGroup, ApiUser, MagicLink, MagicLinkRedirectUri, MagicLinkSecret}; use v_api::endpoints::{ api_user::{ - add_api_user_permission_op, add_api_user_to_group_op, create_api_user_op, create_api_user_token_op, + add_api_user_permission_op, add_api_user_to_group_op, create_api_user_token_op, delete_api_user_token_op, get_api_user_op, list_api_user_op, get_api_user_token_op, get_self_op, link_provider_op, list_api_user_tokens_op, remove_api_user_from_group_op, remove_api_user_permission_op, set_api_user_contact_email_op, list_api_users_for_group_op, - update_api_user_op, AddGroupBody, ApiKeyCreateParams, ApiKeyResponse, ApiUserPath, + AddGroupBody, ApiKeyCreateParams, ApiKeyResponse, ApiUserPath, ApiUserPermissionParams, ApiUserProviderLinkPayload, ApiUserRemoveGroupPath, ApiUserTokenPath, - ApiUserUpdateParams, GetUserResponse, InitialApiKeyResponse, ApiUserEmailUpdateParams, ApiUserGroupPath + GetUserResponse, InitialApiKeyResponse, ApiUserEmailUpdateParams, ApiUserGroupPath }, api_user_provider::{ create_link_token_op, ApiUserLinkRequestPayload, ApiUserLinkRequestResponse, ApiUserProviderPath, }, group::{ - create_group_op, delete_group_op, get_groups_op, update_group_op, AccessGroupPath, - AccessGroupUpdateParams, + add_group_permission_op, create_group_op, delete_group_op, get_groups_op, + remove_group_permission_op, AccessGroupPath, + AccessGroupPermissionParams, AccessGroupUpdateParams, }, login::{ magic_link:: { @@ -61,13 +63,24 @@ mod macros { }, oauth::{ client::{ - create_oauth_client_op, create_oauth_client_redirect_uri_op, - create_oauth_client_secret_op, delete_oauth_client_redirect_uri_op, - delete_oauth_client_secret_op, get_oauth_client_op, list_oauth_clients_op, + add_oauth_client_key_op, add_oauth_client_permission_op, + get_oauth_client_permissions_op, remove_oauth_client_permission_op, + list_service_account_tokens_op, ListServiceAccountTokensPath, + revoke_service_account_token_op, RevokeServiceAccountTokenPath, + OAuthClientPermissionParams, OAuthClientPermissionPath, + create_oauth_client_op, + create_oauth_client_redirect_uri_op, create_oauth_client_secret_op, + delete_oauth_client_key_op, delete_oauth_client_redirect_uri_op, + delete_oauth_client_secret_op, + get_oauth_client_op, list_oauth_clients_op, AddOAuthClientKeyPath, AddOAuthClientRedirectBody, AddOAuthClientRedirectPath, - AddOAuthClientSecretPath, DeleteOAuthClientRedirectPath, - DeleteOAuthClientSecretPath, GetOAuthClientPath, - InitialOAuthClientSecretResponse, + AddOAuthClientSecretPath, DeleteOAuthClientKeyPath, + DeleteOAuthClientRedirectPath, DeleteOAuthClientSecretPath, + GetOAuthClientPath, InitialOAuthClientSecretResponse, + }, + flow::client_credentials::{ + client_credentials_token_op, ClientCredentialsTokenBody, + ClientCredentialsTokenResponse, }, flow::code::{ authz_code_callback_op, authz_code_exchange_op, authz_code_redirect_op, @@ -175,6 +188,94 @@ mod macros { delete_oauth_client_redirect_uri_op(&rqctx, path).await } + /// List the permissions an OAuth client's service account has + #[endpoint { + method = GET, + path = "/oauth/client/{client_id}/service-account/permission" + }] + pub async fn get_oauth_client_permissions( + rqctx: RequestContext<$context_type>, + path: Path, + ) -> Result>, HttpError> { + get_oauth_client_permissions_op(&rqctx, path).await + } + + /// Grant a permission to an OAuth client's service account + #[endpoint { + method = POST, + path = "/oauth/client/{client_id}/service-account/permission" + }] + pub async fn add_oauth_client_permission( + rqctx: RequestContext<$context_type>, + path: Path, + body: TypedBody>, + ) -> Result>, HttpError> { + add_oauth_client_permission_op(&rqctx, path, body.into_inner()).await + } + + /// Remove a permission from an OAuth client's service account + #[endpoint { + method = DELETE, + path = "/oauth/client/{client_id}/service-account/permission" + }] + pub async fn remove_oauth_client_permission( + rqctx: RequestContext<$context_type>, + path: Path, + body: TypedBody>, + ) -> Result>, HttpError> { + remove_oauth_client_permission_op(&rqctx, path, body.into_inner()).await + } + + /// List the service account tokens issued to an OAuth client that have neither + /// expired nor been revoked + #[endpoint { + method = GET, + path = "/oauth/client/{client_id}/service-account/token" + }] + pub async fn list_service_account_tokens( + rqctx: RequestContext<$context_type>, + path: Path, + ) -> Result>, HttpError> { + list_service_account_tokens_op(&rqctx, path).await + } + + /// Revoke one of the service account tokens issued to an OAuth client + #[endpoint { + method = DELETE, + path = "/oauth/client/{client_id}/service-account/token/{token_id}" + }] + pub async fn revoke_service_account_token( + rqctx: RequestContext<$context_type>, + path: Path, + ) -> Result, HttpError> { + revoke_service_account_token_op(&rqctx, path).await + } + + /// Register a public key for an OAuth client's client credential authentication + #[endpoint { + method = POST, + path = "/oauth/client/{client_id}/service-account/key" + }] + pub async fn add_oauth_client_key( + rqctx: RequestContext<$context_type>, + path: Path, + body: TypedBody, + ) -> Result, HttpError> { + add_oauth_client_key_op(&rqctx, path, body).await + } + + /// Remove a public key from an OAuth client + #[endpoint { + method = DELETE, + path = "/oauth/client/{client_id}/service-account/key/{key_id}" + }] + pub async fn delete_oauth_client_key( + rqctx: RequestContext<$context_type>, + path: Path, + ) -> Result, HttpError> { + delete_oauth_client_key_op(&rqctx, path).await + } + // MAGIC LINK CLIENT /// List Magic Link clients @@ -273,7 +374,7 @@ mod macros { rqctx: RequestContext<$context_type>, path: Path, query: Query, - ) -> Result { + ) -> Result { authz_code_redirect_op(&rqctx, path, query).await } @@ -301,7 +402,7 @@ mod macros { query: Query, path: Path, body: TypedBody, - ) -> Result, HttpError> { + ) -> Result>, v_api::endpoints::login::oauth::flow::error::OAuthErrorResponse> { authz_code_exchange_op(&rqctx, query, path, body).await } @@ -344,7 +445,7 @@ mod macros { rqctx: RequestContext<$context_type>, path: Path, body: TypedBody, - ) -> Result, HttpError> { + ) -> Result, v_api::endpoints::login::oauth::flow::error::OAuthErrorResponse> { device_authz_op(&rqctx, path, body).await } @@ -359,10 +460,25 @@ mod macros { rqctx: RequestContext<$context_type>, path: Path, body: TypedBody, - ) -> Result, HttpError> { + ) -> Result, v_api::endpoints::login::oauth::flow::error::OAuthErrorResponse> { exchange_device_token_op(&rqctx, path, body).await } + // CLIENT CREDENTIALS + + /// Issue an access token to an OAuth client for authenticating as a service account + #[endpoint { + method = POST, + path = "/oauth/token", + content_type = "application/x-www-form-urlencoded", + }] + pub async fn client_credentials_token( + rqctx: RequestContext<$context_type>, + body: TypedBody, + ) -> Result>, v_api::endpoints::login::oauth::flow::error::OAuthErrorResponse> { + client_credentials_token_op(&rqctx, body).await + } + // MAGIC LINK /// Send a new magic link authentication link @@ -387,7 +503,7 @@ mod macros { rqctx: RequestContext<$context_type>, _path: Path, body: TypedBody, - ) -> Result, HttpError> { + ) -> Result>, HttpError> { magic_link_exchange_op(&rqctx, body).await } @@ -464,32 +580,6 @@ mod macros { get_api_user_op(&rqctx, path).await } - /// Create a new user - #[endpoint { - method = POST, - path = "/api-user", - }] - pub async fn create_api_user( - rqctx: RequestContext<$context_type>, - body: TypedBody>, - ) -> Result>, HttpError> { - create_api_user_op(&rqctx, body).await - } - - /// Update the permissions assigned to a given user. These replace any existing - /// permissions. - #[endpoint { - method = POST, - path = "/api-user/{user_id}", - }] - pub async fn update_api_user( - rqctx: RequestContext<$context_type>, - path: Path, - body: TypedBody>, - ) -> Result>, HttpError> { - update_api_user_op(&rqctx, path.into_inner(), body.into_inner()).await - } - /// Add a single permission to a user #[endpoint { method = POST, @@ -641,17 +731,30 @@ mod macros { create_group_op(&rqctx, body.into_inner()).await } - /// Update a group + /// Add a permission to a group #[endpoint { - method = PUT, - path = "/group/{group_id}", + method = POST, + path = "/group/{group_id}/permission", }] - pub async fn update_group( + pub async fn add_group_permission( rqctx: RequestContext<$context_type>, path: Path, - body: TypedBody>, + body: TypedBody>, + ) -> Result>, HttpError> { + add_group_permission_op(&rqctx, path.into_inner(), body.into_inner()).await + } + + /// Remove a permission from a group + #[endpoint { + method = DELETE, + path = "/group/{group_id}/permission", + }] + pub async fn remove_group_permission( + rqctx: RequestContext<$context_type>, + path: Path, + body: TypedBody>, ) -> Result>, HttpError> { - update_group_op(&rqctx, path.into_inner(), body.into_inner()).await + remove_group_permission_op(&rqctx, path.into_inner(), body.into_inner()).await } /// Delete a group @@ -750,10 +853,6 @@ mod macros { .expect("Failed to register endpoint"); $api.register(get_api_user) .expect("Failed to register endpoint"); - $api.register(create_api_user) - .expect("Failed to register endpoint"); - $api.register(update_api_user) - .expect("Failed to register endpoint"); $api.register(add_api_user_permission) .expect("Failed to register endpoint"); $api.register(remove_api_user_permission) @@ -784,7 +883,9 @@ mod macros { .expect("Failed to register endpoint"); $api.register(create_group) .expect("Failed to register endpoint"); - $api.register(update_group) + $api.register(add_group_permission) + .expect("Failed to register endpoint"); + $api.register(remove_group_permission) .expect("Failed to register endpoint"); $api.register(delete_group) .expect("Failed to register endpoint"); @@ -812,6 +913,20 @@ mod macros { .expect("Failed to register endpoint"); $api.register(delete_oauth_client_redirect_uri) .expect("Failed to register endpoint"); + $api.register(get_oauth_client_permissions) + .expect("Failed to register endpoint"); + $api.register(add_oauth_client_permission) + .expect("Failed to register endpoint"); + $api.register(remove_oauth_client_permission) + .expect("Failed to register endpoint"); + $api.register(list_service_account_tokens) + .expect("Failed to register endpoint"); + $api.register(revoke_service_account_token) + .expect("Failed to register endpoint"); + $api.register(add_oauth_client_key) + .expect("Failed to register endpoint"); + $api.register(delete_oauth_client_key) + .expect("Failed to register endpoint"); // OAuth Authorization Login $api.register(authz_code_redirect) @@ -831,6 +946,10 @@ mod macros { $api.register(exchange_device_token) .expect("Failed to register endpoint"); + // Client Credentials + $api.register(client_credentials_token) + .expect("Failed to register endpoint"); + // Magic Link Client Management $api.register(list_magic_links) .expect("Failed to register endpoint"); diff --git a/v-api/src/endpoints/login/local/mod.rs b/v-api/src/endpoints/login/local/mod.rs index 3afc3ef0..28fab0f5 100644 --- a/v-api/src/endpoints/login/local/mod.rs +++ b/v-api/src/endpoints/login/local/mod.rs @@ -8,12 +8,16 @@ use http::{Response, StatusCode, header}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use tracing::instrument; +use uuid::Uuid; use v_model::permissions::PermissionStorage; use crate::{ - authn::jwt::Claims, + authn::jwt::UserClaims, context::ApiContext, - endpoints::login::{ExternalUserId, UserInfo, oauth::flow::device_token::ProxyTokenResponse}, + endpoints::login::{ + ExternalUserId, UserInfo, + oauth::flow::{device_token::ProxyTokenResponse, mark_uncacheable}, + }, permissions::{VAppPermission, VPermission}, }; @@ -55,11 +59,12 @@ where &ctx.v_ctx().builtin_registration_user(), ctx.v_ctx().jwt_signer(), &api_user.user.id, - &Claims::new( + &UserClaims::new( ctx.v_ctx(), None, &api_user.user.id, &api_user_provider.id, + Uuid::new_v4(), vec!["full".to_string()], Utc::now() + Duration::seconds(60 * 60), ), @@ -68,7 +73,7 @@ where tracing::info!(provider = "local", api_user_id = ?api_user.user.id, "Generated access token"); - Ok(Response::builder() + let mut token_response = Response::builder() .status(StatusCode::OK) .header(header::CONTENT_TYPE, "application/json") .body( @@ -81,5 +86,8 @@ where }) .unwrap() .into(), - )?) + )?; + mark_uncacheable(token_response.headers_mut()); + + Ok(token_response) } diff --git a/v-api/src/endpoints/login/magic_link/client.rs b/v-api/src/endpoints/login/magic_link/client.rs index c4a4864f..94d99b4e 100644 --- a/v-api/src/endpoints/login/magic_link/client.rs +++ b/v-api/src/endpoints/login/magic_link/client.rs @@ -21,7 +21,7 @@ use crate::{ permissions::{VAppPermission, VPermission}, response::ResourceError, secrets::OpenApiSecretString, - util::response::{bad_request, to_internal_error}, + util::response::{bad_request, forbidden, to_internal_error}, }; #[instrument(skip(rqctx), err(Debug))] @@ -56,7 +56,10 @@ pub async fn create_magic_link_inner( where T: VAppPermission + From + PermissionStorage, { - // Create the new client + // Only users are allowed to create clients. + let creator = caller.user_id().ok_or_else(forbidden)?; + + // Create the new client. let client = ctx.magic_link.create_magic_link(&caller).await?; // Give the caller permission to perform actions on the client they just created. @@ -66,7 +69,7 @@ where ctx.user .add_permissions_to_user( ®istration_caller, - &caller.id, + &creator, vec![ VPermission::GetMagicLinkClient(client.id), VPermission::ManageMagicLinkClient(client.id), @@ -245,7 +248,7 @@ mod tests { use newtype_uuid::TypedUuid; use v_model::{ ApiUser, ApiUserInfo, MagicLink, MagicLinkSecret, - permissions::Caller, + permissions::{Caller, Principal}, storage::{MockApiUserStore, MockMagicLinkSecretStore, MockMagicLinkStore}, }; @@ -273,6 +276,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, } } @@ -280,7 +284,7 @@ mod tests { async fn test_create_client_with_secret() { let user = mock_user(); let mut caller = Caller { - id: user.id, + principal: Principal::User(user.id), permissions: user.permissions.clone(), extensions: HashMap::default(), }; @@ -296,8 +300,8 @@ mod tests { providers: vec![], })) }); - user_store.expect_upsert().returning(|user| { - Ok(ApiUserInfo { + user_store.expect_update().returning(|user, _| { + Ok(Some(ApiUserInfo { user: ApiUser { id: user.id, permissions: user.permissions, @@ -305,10 +309,11 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }, email: None, providers: vec![], - }) + })) }); let mut store = MockMagicLinkStore::new(); diff --git a/v-api/src/endpoints/login/magic_link/mod.rs b/v-api/src/endpoints/login/magic_link/mod.rs index 774bbe47..0926c6e5 100644 --- a/v-api/src/endpoints/login/magic_link/mod.rs +++ b/v-api/src/endpoints/login/magic_link/mod.rs @@ -4,10 +4,10 @@ use chrono::{Duration, Utc}; use dropshot::{ - ClientErrorStatusCode, ErrorStatusCode, HttpError, HttpResponseOk, Path, RequestContext, - TypedBody, + ClientErrorStatusCode, ErrorStatusCode, HttpError, HttpResponseHeaders, HttpResponseOk, Path, + RequestContext, TypedBody, }; -use newtype_uuid::TypedUuid; +use newtype_uuid::{GenericUuid, TypedUuid}; use schemars::JsonSchema; use secrecy::ExposeSecret; use serde::{Deserialize, Serialize}; @@ -25,7 +25,7 @@ use crate::{ ApiContext, VContext, authn::{Verify, key::RawKey}, context::magic_link::{MagicLinkSendError, MagicLinkTransitionError}, - endpoints::login::{ExternalUserId, UserInfo}, + endpoints::login::{ExternalUserId, UserInfo, oauth::flow::token_response}, permissions::VAppPermission, response::{ResourceError, bad_request, internal_error, to_internal_error}, secrets::OpenApiSecretString, @@ -184,7 +184,7 @@ pub struct MagicLinkExchangeResponse { pub async fn magic_link_exchange_op( rqctx: &RequestContext>, body: TypedBody, -) -> Result, HttpError> +) -> Result>, HttpError> where T: VAppPermission + PermissionStorage, { @@ -251,15 +251,16 @@ where &ctx.builtin_registration_user(), &api_user_info.user.id, &api_user_provider.id, + attempt.magic_link_client_id.into_untyped_uuid(), scope, ) .await?; - Ok(HttpResponseOk(MagicLinkExchangeResponse { + Ok(token_response(HttpResponseOk(MagicLinkExchangeResponse { token_type: "Bearer".to_string(), access_token: token.signed_token, expires_in: token.expires_in, - })) + }))) } else { Err(bad_request("Invalid reciption")) } diff --git a/v-api/src/endpoints/login/oauth/client.rs b/v-api/src/endpoints/login/oauth/client.rs index 1357b914..bcba4251 100644 --- a/v-api/src/endpoints/login/oauth/client.rs +++ b/v-api/src/endpoints/login/oauth/client.rs @@ -9,17 +9,18 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use tracing::instrument; use v_model::{ - OAuthClient, OAuthClientId, OAuthClientRedirectUri, OAuthClientSecret, OAuthRedirectUriId, - OAuthSecretId, - permissions::{Caller, PermissionStorage}, + OAuthClient, OAuthClientId, OAuthClientKey, OAuthClientKeyId, OAuthClientRedirectUri, + OAuthClientSecret, OAuthRedirectUriId, OAuthSecretId, Permissions, ServiceAccountToken, + ServiceAccountTokenId, + permissions::{Caller, Permission, PermissionStorage}, }; use crate::{ VContext, - authn::key::RawKey, + authn::{client_key::SubmittedJwk, key::RawKey}, context::{ApiContext, VContextWithCaller, oauth::OAuthError}, permissions::{VAppPermission, VPermission}, - response::{ResourceError, bad_request}, + response::{ResourceError, bad_request, forbidden}, secrets::OpenApiSecretString, util::response::to_internal_error, }; @@ -54,6 +55,9 @@ pub async fn create_oauth_client_inner( where T: VAppPermission + From + PermissionStorage, { + // Only users are allowed to create clients. + let creator = caller.user_id().ok_or_else(forbidden)?; + // Create the new client let client = ctx .oauth @@ -67,7 +71,7 @@ where ctx.user .add_permissions_to_user( ®istration_caller, - &caller.id, + &creator, vec![ VPermission::GetOAuthClient(client.id), VPermission::ManageOAuthClient(client.id), @@ -99,6 +103,248 @@ where )) } +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub struct OAuthClientPermissionPath { + pub client_id: TypedUuid, +} + +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub struct OAuthClientPermissionParams { + pub permission: T, +} + +fn into_permissions_response(permissions: Permissions) -> Permissions +where + T: Permission, + U: Permission + From, +{ + permissions.into_iter().map(|p| p.into()).collect() +} + +/// Lists the permissions a client holds when it acts as a service account. +#[instrument(skip(rqctx), err(Debug))] +pub async fn get_oauth_client_permissions_op( + rqctx: &RequestContext>, + path: Path, +) -> Result>, HttpError> +where + T: VAppPermission + PermissionStorage, + U: Permission + From + JsonSchema, +{ + let (ctx, caller) = rqctx.as_ctx().await?; + let client_id = path.into_inner().client_id; + Ok(HttpResponseOk(into_permissions_response( + ctx.oauth + .get_service_account_permissions(&caller, &client_id) + .await?, + ))) +} + +/// Grants a single permission to a client's service account. The caller must be able to manage +/// the client and grant the permission. +#[instrument(skip(rqctx, body), err(Debug))] +pub async fn add_oauth_client_permission_op( + rqctx: &RequestContext>, + path: Path, + body: OAuthClientPermissionParams, +) -> Result>, HttpError> +where + T: VAppPermission + PermissionStorage, + U: Permission + From + JsonSchema, +{ + let (ctx, caller) = rqctx.as_ctx().await?; + add_oauth_client_permission_inner(ctx, caller, &path.into_inner().client_id, body).await +} + +#[instrument(skip(ctx, caller, body), err(Debug))] +pub async fn add_oauth_client_permission_inner( + ctx: &VContext, + caller: Caller, + client_id: &TypedUuid, + body: OAuthClientPermissionParams, +) -> Result>, HttpError> +where + T: VAppPermission + PermissionStorage, + U: Permission + From + JsonSchema, +{ + Ok(HttpResponseOk(into_permissions_response( + ctx.oauth + .add_permission_to_service_account(&caller, client_id, body.permission) + .await?, + ))) +} + +/// Removes a single permission from a client's service account. The caller must be able to +/// manage the client and grant the permission being removed. +#[instrument(skip(rqctx, body), err(Debug))] +pub async fn remove_oauth_client_permission_op( + rqctx: &RequestContext>, + path: Path, + body: OAuthClientPermissionParams, +) -> Result>, HttpError> +where + T: VAppPermission + PermissionStorage, + U: Permission + From + JsonSchema, +{ + let (ctx, caller) = rqctx.as_ctx().await?; + remove_oauth_client_permission_inner(ctx, caller, &path.into_inner().client_id, body).await +} + +#[instrument(skip(ctx, caller, body), err(Debug))] +pub async fn remove_oauth_client_permission_inner( + ctx: &VContext, + caller: Caller, + client_id: &TypedUuid, + body: OAuthClientPermissionParams, +) -> Result>, HttpError> +where + T: VAppPermission + PermissionStorage, + U: Permission + From + JsonSchema, +{ + Ok(HttpResponseOk(into_permissions_response( + ctx.oauth + .remove_permission_from_service_account(&caller, client_id, &body.permission) + .await?, + ))) +} + +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub struct AddOAuthClientKeyPath { + pub client_id: TypedUuid, +} + +// TODO: Only Ed25519 keys are accepted currently. We need to expand this. +/// Registers the public half of a key pair that a client signs its client credentials assertions +/// with. The client keeps the private key, and its assertions are verified against this public +/// key. +#[instrument(skip(rqctx, body), err(Debug))] +pub async fn add_oauth_client_key_op( + rqctx: &RequestContext>, + path: Path, + body: TypedBody, +) -> Result, HttpError> +where + T: VAppPermission + PermissionStorage, +{ + let (ctx, caller) = rqctx.as_ctx().await?; + add_oauth_client_key_inner(ctx, caller, &path.into_inner().client_id, body.into_inner()).await +} + +#[instrument(skip(ctx, caller, jwk), err(Debug))] +pub async fn add_oauth_client_key_inner( + ctx: &VContext, + caller: Caller, + client_id: &TypedUuid, + jwk: SubmittedJwk, +) -> Result, HttpError> +where + T: VAppPermission + PermissionStorage, +{ + Ok(HttpResponseOk( + ctx.oauth + .add_oauth_client_key(&caller, client_id, jwk.into_public_jwk()) + .await + .map_err(|err| match err { + ResourceError::InternalError(OAuthError::ClientKey(err)) => bad_request(err), + err => err.into(), + })?, + )) +} + +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub struct ListServiceAccountTokensPath { + pub client_id: TypedUuid, +} + +/// Lists the service account tokens issued to a client that have neither expired nor been revoked +#[instrument(skip(rqctx), err(Debug))] +pub async fn list_service_account_tokens_op( + rqctx: &RequestContext>, + path: Path, +) -> Result>, HttpError> +where + T: VAppPermission + PermissionStorage, +{ + let (ctx, caller) = rqctx.as_ctx().await?; + list_service_account_tokens_inner(ctx, caller, &path.into_inner().client_id).await +} + +pub async fn list_service_account_tokens_inner( + ctx: &VContext, + caller: Caller, + client_id: &TypedUuid, +) -> Result>, HttpError> +where + T: VAppPermission + PermissionStorage, +{ + Ok(HttpResponseOk( + ctx.oauth + .list_service_account_tokens(&caller, client_id) + .await?, + )) +} + +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub struct RevokeServiceAccountTokenPath { + pub client_id: TypedUuid, + pub token_id: TypedUuid, +} + +/// Revokes one of a client's service account tokens so that it is refused from then on +#[instrument(skip(rqctx), err(Debug))] +pub async fn revoke_service_account_token_op( + rqctx: &RequestContext>, + path: Path, +) -> Result, HttpError> +where + T: VAppPermission + PermissionStorage, +{ + let (ctx, caller) = rqctx.as_ctx().await?; + let path = path.into_inner(); + revoke_service_account_token_inner(ctx, caller, &path.client_id, &path.token_id).await +} + +pub async fn revoke_service_account_token_inner( + ctx: &VContext, + caller: Caller, + client_id: &TypedUuid, + token_id: &TypedUuid, +) -> Result, HttpError> +where + T: VAppPermission + PermissionStorage, +{ + Ok(HttpResponseOk( + ctx.oauth + .revoke_service_account_token(&caller, client_id, token_id) + .await?, + )) +} + +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub struct DeleteOAuthClientKeyPath { + pub client_id: TypedUuid, + pub key_id: TypedUuid, +} + +/// Removes one of a client's public keys. Tokens already issued for assertions from this key pair +/// are not revoked. +#[instrument(skip(rqctx), err(Debug))] +pub async fn delete_oauth_client_key_op( + rqctx: &RequestContext>, + path: Path, +) -> Result, HttpError> +where + T: VAppPermission + PermissionStorage, +{ + let (ctx, caller) = rqctx.as_ctx().await?; + let path = path.into_inner(); + Ok(HttpResponseOk( + ctx.oauth + .delete_oauth_client_key(&caller, &path.client_id, &path.key_id) + .await?, + )) +} + #[derive(Debug, Clone, Deserialize, JsonSchema)] pub struct AddOAuthClientSecretPath { pub client_id: TypedUuid, @@ -240,12 +486,21 @@ mod tests { }; use chrono::Utc; + use http::StatusCode; use mockall::predicate::eq; use newtype_uuid::TypedUuid; + use serde_json::json; use v_model::{ - ApiUser, ApiUserInfo, OAuthClient, OAuthClientSecret, - permissions::Caller, - storage::{MockApiUserStore, MockOAuthClientSecretStore, MockOAuthClientStore}, + ApiUser, ApiUserInfo, NewOAuthClientKey, NewServiceAccount, OAuthClient, OAuthClientId, + OAuthClientKey, OAuthClientSecret, Permissions, ServiceAccount, ServiceAccountToken, + ServiceAccountTokenId, + jwk::PublicJwk, + permissions::{Caller, Principal}, + storage::{ + MockApiUserStore, MockOAuthClientAssertionStore, MockOAuthClientKeyStore, + MockOAuthClientSecretStore, MockOAuthClientStore, MockServiceAccountStore, + MockServiceAccountTokenStore, ServiceAccountTokenFilter, StoreError, + }, }; use crate::{ @@ -253,9 +508,15 @@ mod tests { context::test_mocks::{MockStorage, mock_context}, endpoints::login::oauth::{ CheckOAuthClient, - client::{create_oauth_client_inner, create_oauth_client_secret_inner}, + client::{ + OAuthClientPermissionParams, add_oauth_client_key_inner, + add_oauth_client_permission_inner, create_oauth_client_inner, + create_oauth_client_secret_inner, list_service_account_tokens_inner, + remove_oauth_client_permission_inner, revoke_service_account_token_inner, + }, }, permissions::VPermission, + util::tests::get_status, }; fn mock_user() -> ApiUser { @@ -272,6 +533,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, } } @@ -279,7 +541,7 @@ mod tests { async fn test_create_client_with_secret() { let user = mock_user(); let mut caller = Caller { - id: user.id, + principal: Principal::User(user.id), permissions: user.permissions.clone(), extensions: HashMap::default(), }; @@ -295,8 +557,8 @@ mod tests { providers: vec![], })) }); - user_store.expect_upsert().returning(|user| { - Ok(ApiUserInfo { + user_store.expect_update().returning(|user, _| { + Ok(Some(ApiUserInfo { user: ApiUser { id: user.id, permissions: user.permissions, @@ -304,22 +566,27 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }, email: None, providers: vec![], - }) + })) }); let mut store = MockOAuthClientStore::new(); store.expect_upsert().returning(|client| { Ok(OAuthClient { id: client.id, + keys: vec![], secrets: vec![], redirect_uris: vec![], created_at: Utc::now(), deleted_at: None, }) }); + store + .expect_get() + .returning(|id, _| Ok(Some(oauth_client(*id, vec![])))); let last_stored_secret = Arc::new(Mutex::new(None)); @@ -352,6 +619,9 @@ mod tests { .await .unwrap() .0; + caller + .permissions + .insert(VPermission::GetOAuthClient(client.id)); caller .permissions .insert(VPermission::ManageOAuthClient(client.id)); @@ -368,4 +638,710 @@ mod tests { assert!(client.is_secret_valid(&key, &ctx)) } + + fn oauth_client(id: TypedUuid, keys: Vec) -> OAuthClient { + OAuthClient { + id, + secrets: vec![], + redirect_uris: vec![], + keys, + created_at: Utc::now(), + deleted_at: None, + } + } + + fn caller_with(permissions: Vec) -> Caller { + Caller { + principal: Principal::User(TypedUuid::new_v4()), + permissions: permissions.into(), + extensions: HashMap::default(), + } + } + + /// The example Ed25519 public key from RFC 8037 Appendix A.2 + const RFC_8037_X: &str = "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"; + + fn submitted(jwk: serde_json::Value) -> crate::authn::client_key::SubmittedJwk { + serde_json::from_value(jwk).unwrap() + } + + fn valid_jwk() -> serde_json::Value { + json!({ + "kty": "OKP", + "crv": "Ed25519", + "x": RFC_8037_X, + "use": "sig", + "key_ops": ["verify"], + "alg": "EdDSA", + }) + } + + fn stored_key(key: NewOAuthClientKey) -> OAuthClientKey { + OAuthClientKey { + id: key.id, + oauth_client_id: key.oauth_client_id, + thumbprint: key.thumbprint, + jwk: key.jwk, + created_at: Utc::now(), + deleted_at: None, + } + } + + /// A context holding one client with `keys`. Inserting a key reports a conflict when + /// `duplicate` is set, as storage does for a thumbprint registered anywhere before. + async fn key_ctx( + client_id: TypedUuid, + keys: Vec, + duplicate: bool, + ) -> ( + crate::VContext, + Arc>>, + ) { + let inserted = Arc::new(Mutex::new(vec![])); + + let mut client_store = MockOAuthClientStore::new(); + client_store + .expect_get() + .withf(move |id, _| id == &client_id) + .returning(move |id, _| Ok(Some(oauth_client(*id, keys.clone())))); + + let mut key_store = MockOAuthClientKeyStore::new(); + let recorder = inserted.clone(); + key_store.expect_insert().returning(move |key| { + recorder.lock().unwrap().push(key.clone()); + if duplicate { + Err(StoreError::Conflict) + } else { + Ok(stored_key(key)) + } + }); + key_store.expect_delete().returning(|id| { + Ok(Some(stored_key(NewOAuthClientKey { + id: *id, + oauth_client_id: TypedUuid::new_v4(), + thumbprint: "thumbprint".to_string(), + jwk: PublicJwk::ed25519([7; 32]), + }))) + }); + + let mut storage = MockStorage::new(); + storage.oauth_client_store = Some(Arc::new(client_store)); + storage.oauth_client_key_store = Some(Arc::new(key_store)); + + (mock_context(Arc::new(storage)).await, inserted) + } + + fn key_manager(client_id: TypedUuid) -> Caller { + caller_with(vec![ + VPermission::GetOAuthClient(client_id), + VPermission::ManageOAuthClient(client_id), + ]) + } + + /// A registered key is stored against its client with its thumbprint as its id + #[tokio::test] + async fn adding_a_key_stores_it_under_its_thumbprint() { + let client_id = TypedUuid::new_v4(); + let (ctx, inserted) = key_ctx(client_id, vec![], false).await; + + let resp = add_oauth_client_key_inner( + &ctx, + key_manager(client_id), + &client_id, + submitted(valid_jwk()), + ) + .await; + assert_eq!(get_status(&resp), StatusCode::OK); + + let inserted = inserted.lock().unwrap(); + assert_eq!(client_id, inserted[0].oauth_client_id); + assert_eq!( + "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k", + inserted[0].thumbprint + ); + } + + #[tokio::test] + async fn adding_a_key_requires_managing_the_client() { + let client_id = TypedUuid::new_v4(); + let (ctx, inserted) = key_ctx(client_id, vec![], false).await; + + let can_only_see = caller_with(vec![VPermission::GetOAuthClient(client_id)]); + let resp = + add_oauth_client_key_inner(&ctx, can_only_see, &client_id, submitted(valid_jwk())) + .await; + assert_eq!(get_status(&resp), StatusCode::FORBIDDEN); + assert!(inserted.lock().unwrap().is_empty()); + } + + /// A key registered anywhere before, by any client, can not be registered again + #[tokio::test] + async fn adding_a_registered_key_is_a_conflict() { + let client_id = TypedUuid::new_v4(); + let (ctx, _) = key_ctx(client_id, vec![], true).await; + + let resp = add_oauth_client_key_inner( + &ctx, + key_manager(client_id), + &client_id, + submitted(valid_jwk()), + ) + .await; + assert_eq!(get_status(&resp), StatusCode::CONFLICT); + } + + /// A key can only be removed through the client it belongs to, by a caller who manages it + #[tokio::test] + async fn removing_a_key_requires_it_to_belong_to_the_client() { + let client_id = TypedUuid::new_v4(); + let key = stored_key(NewOAuthClientKey { + id: TypedUuid::new_v4(), + oauth_client_id: client_id, + thumbprint: "thumbprint".to_string(), + jwk: PublicJwk::ed25519([7; 32]), + }); + let key_id = key.id; + let (ctx, _) = key_ctx(client_id, vec![key], false).await; + + let removed = ctx + .oauth + .delete_oauth_client_key(&key_manager(client_id), &client_id, &key_id) + .await; + assert!(removed.is_ok()); + + let not_on_client = ctx + .oauth + .delete_oauth_client_key(&key_manager(client_id), &client_id, &TypedUuid::new_v4()) + .await; + assert!(matches!( + not_on_client, + Err(crate::response::ResourceError::DoesNotExist) + )); + + let can_only_see = caller_with(vec![VPermission::GetOAuthClient(client_id)]); + let refused = ctx + .oauth + .delete_oauth_client_key(&can_only_see, &client_id, &key_id) + .await; + assert!(matches!( + refused, + Err(crate::response::ResourceError::Restricted) + )); + } + + /// A service account can not create a client, and is refused before the client is created so + /// that no client is left without anyone able to manage it + #[tokio::test] + async fn a_service_account_can_not_create_a_client() { + let mut client_store = MockOAuthClientStore::new(); + client_store.expect_upsert().never(); + let mut storage = MockStorage::new(); + storage.oauth_client_store = Some(Arc::new(client_store)); + let ctx = mock_context(Arc::new(storage)).await; + + let service_account = Caller { + principal: Principal::ServiceAccount(TypedUuid::new_v4()), + permissions: vec![VPermission::CreateOAuthClient].into(), + extensions: HashMap::default(), + }; + + let resp = create_oauth_client_inner(&ctx, service_account).await; + assert_eq!(get_status(&resp), StatusCode::FORBIDDEN); + } + + /// How a service account write is answered + #[derive(Clone, Copy)] + enum WriteOutcome { + Lands, + Stale, + } + + /// What service account changes wrote, as the record and the generation an update expected + #[derive(Default)] + struct AccountWrites { + created: Vec>, + updated: Vec<(NewServiceAccount, i64)>, + } + + fn service_account( + id: TypedUuid, + permissions: Permissions, + generation: i64, + ) -> ServiceAccount { + ServiceAccount { + id, + permissions, + created_at: Utc::now(), + updated_at: Utc::now(), + generation, + } + } + + /// A context holding one client, whose service account holds `existing` when it is set + async fn account_ctx( + client_id: TypedUuid, + existing: Option>, + outcome: WriteOutcome, + ) -> (crate::VContext, Arc>) { + let writes = Arc::new(Mutex::new(AccountWrites::default())); + + let mut client_store = MockOAuthClientStore::new(); + client_store + .expect_get() + .withf(move |id, _| id == &client_id) + .returning(move |id, _| Ok(Some(oauth_client(*id, vec![])))); + + let mut account_store = MockServiceAccountStore::new(); + account_store + .expect_get() + .returning(move |_| Ok(existing.clone())); + let recorder = writes.clone(); + account_store.expect_create().returning(move |account| { + recorder.lock().unwrap().created.push(account.clone()); + match outcome { + WriteOutcome::Lands => Ok(service_account(account.id, account.permissions, 0)), + WriteOutcome::Stale => Err(StoreError::Conflict), + } + }); + let recorder = writes.clone(); + account_store + .expect_update() + .returning(move |account, generation| { + recorder + .lock() + .unwrap() + .updated + .push((account.clone(), generation)); + match outcome { + WriteOutcome::Lands => Ok(Some(service_account( + account.id, + account.permissions, + generation + 1, + ))), + WriteOutcome::Stale => Ok(None), + } + }); + + let mut storage = MockStorage::new(); + storage.oauth_client_store = Some(Arc::new(client_store)); + storage.service_account_store = Some(Arc::new(account_store)); + + (mock_context(Arc::new(storage)).await, writes) + } + + fn client_manager( + client_id: TypedUuid, + holds: Vec, + ) -> Caller { + let mut permissions = vec![ + VPermission::GetOAuthClient(client_id), + VPermission::ManageOAuthClient(client_id), + ]; + permissions.extend(holds); + caller_with(permissions) + } + + fn grant(permission: VPermission) -> OAuthClientPermissionParams { + OAuthClientPermissionParams { permission } + } + + /// Granting needs management of the client and the ability to grant the permission + #[tokio::test] + async fn granting_to_a_service_account_requires_grant() { + let client_id = TypedUuid::new_v4(); + let (ctx, writes) = account_ctx(client_id, None, WriteOutcome::Lands).await; + + let cannot_grant = client_manager(client_id, vec![]); + let resp = add_oauth_client_permission_inner::( + &ctx, + cannot_grant, + &client_id, + grant(VPermission::CreateGroup), + ) + .await; + assert_eq!(get_status(&resp), StatusCode::FORBIDDEN); + + let cannot_manage = caller_with(vec![ + VPermission::GetOAuthClient(client_id), + VPermission::CreateGroup, + ]); + let resp = add_oauth_client_permission_inner::( + &ctx, + cannot_manage, + &client_id, + grant(VPermission::CreateGroup), + ) + .await; + assert_eq!(get_status(&resp), StatusCode::FORBIDDEN); + + let writes = writes.lock().unwrap(); + assert!(writes.created.is_empty() && writes.updated.is_empty()); + } + + /// The first permission a client is granted creates its service account + #[tokio::test] + async fn the_first_grant_creates_the_service_account() { + let client_id = TypedUuid::new_v4(); + let (ctx, writes) = account_ctx(client_id, None, WriteOutcome::Lands).await; + + let resp = add_oauth_client_permission_inner::( + &ctx, + client_manager(client_id, vec![VPermission::CreateGroup]), + &client_id, + grant(VPermission::CreateGroup), + ) + .await + .unwrap(); + assert!(resp.0.can(&VPermission::CreateGroup)); + + let writes = writes.lock().unwrap(); + assert_eq!(1, writes.created.len()); + assert!(writes.updated.is_empty()); + assert!(writes.created[0].permissions.can(&VPermission::CreateGroup)); + } + + /// Later grants write against the generation that was read, keeping what the account held + #[tokio::test] + async fn later_grants_update_from_the_generation_read() { + let client_id = TypedUuid::new_v4(); + let existing = service_account(client_id, vec![VPermission::CreateMapper].into(), 4); + let (ctx, writes) = account_ctx(client_id, Some(existing), WriteOutcome::Lands).await; + + add_oauth_client_permission_inner::( + &ctx, + client_manager(client_id, vec![VPermission::CreateGroup]), + &client_id, + grant(VPermission::CreateGroup), + ) + .await + .unwrap(); + + let writes = writes.lock().unwrap(); + assert!(writes.created.is_empty()); + let (written, generation) = &writes.updated[0]; + assert_eq!(4, *generation); + assert!(written.permissions.can(&VPermission::CreateGroup)); + assert!(written.permissions.can(&VPermission::CreateMapper)); + } + + /// Removing needs the ability to grant the permission, and removing one value of a stored set + /// keeps the rest of that set + #[tokio::test] + async fn removing_from_a_service_account_requires_grant() { + let client_id = TypedUuid::new_v4(); + let (a, b) = (TypedUuid::new_v4(), TypedUuid::new_v4()); + let existing = service_account( + client_id, + vec![VPermission::ManageGroups([a, b].into())].into(), + 0, + ); + let (ctx, writes) = account_ctx(client_id, Some(existing), WriteOutcome::Lands).await; + + let resp = remove_oauth_client_permission_inner::( + &ctx, + client_manager(client_id, vec![]), + &client_id, + grant(VPermission::ManageGroup(a)), + ) + .await; + assert_eq!(get_status(&resp), StatusCode::FORBIDDEN); + assert!(writes.lock().unwrap().updated.is_empty()); + + let removed = remove_oauth_client_permission_inner::( + &ctx, + client_manager(client_id, vec![VPermission::ManageGroup(a)]), + &client_id, + grant(VPermission::ManageGroup(a)), + ) + .await + .unwrap(); + assert!(!removed.0.can(&VPermission::ManageGroup(a))); + assert!(removed.0.can(&VPermission::ManageGroup(b))); + } + + /// Losing to a concurrent write is a conflict whether the service account was being created + /// or updated, and is never retried + #[tokio::test] + async fn a_stale_service_account_write_is_a_conflict() { + let client_id = TypedUuid::new_v4(); + let caller = || client_manager(client_id, vec![VPermission::CreateGroup]); + + let (creating, _) = account_ctx(client_id, None, WriteOutcome::Stale).await; + let resp = add_oauth_client_permission_inner::( + &creating, + caller(), + &client_id, + grant(VPermission::CreateGroup), + ) + .await; + assert_eq!(get_status(&resp), StatusCode::CONFLICT); + + let existing = service_account(client_id, Permissions::new(), 2); + let (updating, _) = account_ctx(client_id, Some(existing), WriteOutcome::Stale).await; + let resp = add_oauth_client_permission_inner::( + &updating, + caller(), + &client_id, + grant(VPermission::CreateGroup), + ) + .await; + assert_eq!(get_status(&resp), StatusCode::CONFLICT); + } + + /// Reading needs the client to be visible, and a client never granted anything holds nothing + #[tokio::test] + async fn reading_service_account_permissions() { + let client_id = TypedUuid::new_v4(); + let (ctx, _) = account_ctx(client_id, None, WriteOutcome::Lands).await; + + let can_see = caller_with(vec![VPermission::GetOAuthClient(client_id)]); + let permissions = ctx + .oauth + .get_service_account_permissions(&can_see, &client_id) + .await + .unwrap(); + assert!(permissions.is_empty()); + + let cannot_see = caller_with(vec![VPermission::ManageOAuthClient(client_id)]); + let refused = ctx + .oauth + .get_service_account_permissions(&cannot_see, &client_id) + .await; + assert!(matches!( + refused, + Err(crate::response::ResourceError::Restricted) + )); + } + + fn token_ctx_storage( + client_id: TypedUuid, + ) -> (MockStorage, Arc>>) { + let mut client_store = MockOAuthClientStore::new(); + client_store.expect_get().returning(move |id, deleted| { + Ok((id == &client_id && !deleted).then(|| oauth_client(*id, vec![]))) + }); + + let filters = Arc::new(Mutex::new(vec![])); + let seen = filters.clone(); + let mut token_store = MockServiceAccountTokenStore::new(); + token_store.expect_list().returning(move |filter, _| { + let oauth_client_id = filter.oauth_client_id.clone().unwrap_or_default()[0]; + seen.lock().unwrap().push(filter); + Ok(vec![ServiceAccountToken { + id: TypedUuid::new_v4(), + oauth_client_id, + expires_at: Utc::now(), + revoked_at: None, + created_at: Utc::now(), + updated_at: Utc::now(), + }]) + }); + + let mut storage = MockStorage::new(); + storage.oauth_client_store = Some(Arc::new(client_store)); + storage.service_account_token_store = Some(Arc::new(token_store)); + (storage, filters) + } + + /// Listing tokens needs the client to be visible, and only asks for the client's live tokens + #[tokio::test] + async fn listing_service_account_tokens() { + let client_id = TypedUuid::new_v4(); + let (storage, filters) = token_ctx_storage(client_id); + let ctx = mock_context(Arc::new(storage)).await; + + let tokens = list_service_account_tokens_inner( + &ctx, + caller_with(vec![VPermission::GetOAuthClient(client_id)]), + &client_id, + ) + .await + .unwrap() + .0; + assert_eq!(1, tokens.len()); + assert_eq!( + vec![ServiceAccountTokenFilter { + oauth_client_id: Some(vec![client_id]), + revoked: false, + expired: false, + }], + *filters.lock().unwrap() + ); + + let refused = list_service_account_tokens_inner( + &ctx, + caller_with(vec![VPermission::ManageOAuthClient(client_id)]), + &client_id, + ) + .await; + assert_eq!(StatusCode::FORBIDDEN, get_status(&refused)); + + let missing = TypedUuid::new_v4(); + let not_found = list_service_account_tokens_inner( + &ctx, + caller_with(vec![VPermission::GetOAuthClient(missing)]), + &missing, + ) + .await; + assert_eq!(StatusCode::NOT_FOUND, get_status(¬_found)); + assert_eq!(1, filters.lock().unwrap().len()); + } + + /// Removing expired assertions spans every client, so it needs management of all of them + #[tokio::test] + async fn deleting_expired_client_assertions_requires_managing_every_client() { + let mut assertion_store = MockOAuthClientAssertionStore::new(); + assertion_store + .expect_delete_expired() + .times(1) + .returning(|_| Ok(3)); + + let mut storage = MockStorage::new(); + storage.oauth_client_assertion_store = Some(Arc::new(assertion_store)); + let ctx = mock_context(Arc::new(storage)).await; + + let refused = ctx + .oauth + .delete_expired_client_assertions(&caller_with(vec![VPermission::ManageOAuthClient( + TypedUuid::new_v4(), + )])) + .await; + assert!(matches!( + refused, + Err(crate::response::ResourceError::Restricted) + )); + + let removed = ctx + .oauth + .delete_expired_client_assertions(&caller_with(vec![ + VPermission::ManageOAuthClientsAll, + ])) + .await + .unwrap(); + assert_eq!(3, removed); + } + + /// Revoking needs management of the client, and only revokes live tokens the client holds + #[tokio::test] + async fn revoking_a_service_account_token() { + let client_id = TypedUuid::new_v4(); + let live = TypedUuid::new_v4(); + let foreign = TypedUuid::new_v4(); + let revoked = Arc::new(Mutex::new(vec![])); + + let mut client_store = MockOAuthClientStore::new(); + client_store.expect_get().returning(move |id, deleted| { + Ok((id == &client_id && !deleted).then(|| oauth_client(*id, vec![]))) + }); + + let token = + move |id: TypedUuid, oauth_client_id| ServiceAccountToken { + id, + oauth_client_id, + expires_at: Utc::now(), + revoked_at: None, + created_at: Utc::now(), + updated_at: Utc::now(), + }; + let mut token_store = MockServiceAccountTokenStore::new(); + token_store.expect_get().returning(move |id, revoked| { + assert!(!revoked, "revoked tokens should never be looked up"); + Ok(if id == &live { + Some(token(live, client_id)) + } else if id == &foreign { + Some(token(foreign, TypedUuid::new_v4())) + } else { + None + }) + }); + let recorder = revoked.clone(); + token_store.expect_revoke().returning(move |id| { + recorder.lock().unwrap().push(*id); + Ok(Some(token(*id, client_id))) + }); + + let mut storage = MockStorage::new(); + storage.oauth_client_store = Some(Arc::new(client_store)); + storage.service_account_token_store = Some(Arc::new(token_store)); + let ctx = mock_context(Arc::new(storage)).await; + + let manager = || { + caller_with(vec![ + VPermission::GetOAuthClient(client_id), + VPermission::ManageOAuthClient(client_id), + ]) + }; + + let refused = revoke_service_account_token_inner( + &ctx, + caller_with(vec![VPermission::GetOAuthClient(client_id)]), + &client_id, + &live, + ) + .await; + assert_eq!(StatusCode::FORBIDDEN, get_status(&refused)); + + for missing in [foreign, TypedUuid::new_v4()] { + let resp = + revoke_service_account_token_inner(&ctx, manager(), &client_id, &missing).await; + assert_eq!(StatusCode::NOT_FOUND, get_status(&resp)); + } + assert!(revoked.lock().unwrap().is_empty()); + + let resp = revoke_service_account_token_inner(&ctx, manager(), &client_id, &live) + .await + .unwrap(); + assert_eq!(live, resp.0.id); + assert_eq!(vec![live], *revoked.lock().unwrap()); + } + + /// A client that is deleted or does not exist is not found for every service account + /// permission operation, even for a caller who could otherwise make the change. Its service + /// account is never read or written. + #[tokio::test] + async fn service_account_permissions_of_a_missing_client_are_not_found() { + let client_id = TypedUuid::new_v4(); + + // A deleted client is filtered out by the lookup in the same way as one that never + // existed, so both are represented by the store finding nothing + let mut client_store = MockOAuthClientStore::new(); + client_store + .expect_get() + .withf(move |id, deleted| id == &client_id && !deleted) + .returning(|_, _| Ok(None)); + + let mut storage = MockStorage::new(); + storage.oauth_client_store = Some(Arc::new(client_store)); + storage.service_account_store = Some(Arc::new(MockServiceAccountStore::new())); + let ctx = mock_context(Arc::new(storage)).await; + + let caller = || client_manager(client_id, vec![VPermission::CreateGroup]); + + let read = ctx + .oauth + .get_service_account_permissions(&caller(), &client_id) + .await; + assert!(matches!( + read, + Err(crate::response::ResourceError::DoesNotExist) + )); + + let added = add_oauth_client_permission_inner::( + &ctx, + caller(), + &client_id, + grant(VPermission::CreateGroup), + ) + .await; + assert_eq!(StatusCode::NOT_FOUND, get_status(&added)); + + let removed = remove_oauth_client_permission_inner::( + &ctx, + caller(), + &client_id, + grant(VPermission::CreateGroup), + ) + .await; + assert_eq!(StatusCode::NOT_FOUND, get_status(&removed)); + } } diff --git a/v-api/src/endpoints/login/oauth/flow/client_credentials.rs b/v-api/src/endpoints/login/oauth/flow/client_credentials.rs new file mode 100644 index 00000000..d8d10ef2 --- /dev/null +++ b/v-api/src/endpoints/login/oauth/flow/client_credentials.rs @@ -0,0 +1,686 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +use dropshot::{ + ErrorStatusCode, HttpError, HttpResponseHeaders, HttpResponseOk, RequestContext, TypedBody, +}; +use http::header::AUTHORIZATION; +use newtype_uuid::TypedUuid; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use tracing::instrument; +use v_model::{OAuthClientId, permissions::PermissionStorage}; + +use super::{ + error::{OAuthErrorCode, OAuthErrorResponse}, + requested_scope, token_response, +}; +use crate::{ + authn::client_assertion::JWT_BEARER_ASSERTION_TYPE, + context::{ApiContext, ClientAuthenticationError, VContext}, + permissions::VAppPermission, + secrets::OpenApiSecretString, +}; + +/// A client credentials token request (RFC 6749 §4.4.2) where the client authenticates with a +/// JWT assertion (RFC 7523 §2.2) +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ClientCredentialsTokenBody { + pub grant_type: String, + /// Space delimited scopes that narrow what the token may do. An absent scope means no + /// permissions. Use "full" for every permission the service account holds. + pub scope: Option, + pub client_assertion_type: Option, + pub client_assertion: Option, + /// Optional. When present it must name the client that issued the assertion. + pub client_id: Option>, + /// Never accepted. It is only read so that a request carrying it can be refused. + pub client_secret: Option, +} + +#[derive(Debug, Deserialize, JsonSchema, Serialize)] +pub struct ClientCredentialsTokenResponse { + pub access_token: String, + pub token_type: String, + pub expires_in: i64, + /// The scope granted to the access token per RFC 6749 §5.1 + pub scope: String, +} + +fn invalid_request(description: &str) -> OAuthErrorResponse { + OAuthErrorResponse::new(OAuthErrorCode::InvalidRequest, Some(description)) +} + +fn invalid_client(description: &str) -> OAuthErrorResponse { + OAuthErrorResponse::new(OAuthErrorCode::InvalidClient, Some(description)) + .with_status(ErrorStatusCode::UNAUTHORIZED) +} + +/// The client assertion a token request authenticates with. +/// +/// The request must ask for the client credentials grant with a JWT assertion. A client +/// authenticates in exactly one way, so a request that also carries basic credentials, a bearer +/// token, or a client secret is refused rather than authenticated by whichever of them happens to +/// be checked. A caller supplying any of those has misunderstood how assertions work against this +/// API. +fn client_assertion<'a>( + headers: &http::HeaderMap, + body: &'a ClientCredentialsTokenBody, +) -> Result<&'a str, OAuthErrorResponse> { + if body.grant_type != "client_credentials" { + Err(OAuthErrorResponse::new( + OAuthErrorCode::UnsupportedGrantType, + None, + )) + } else if body.client_assertion_type.as_deref() != Some(JWT_BEARER_ASSERTION_TYPE) { + Err(invalid_request( + "client_assertion_type must be urn:ietf:params:oauth:client-assertion-type:jwt-bearer", + )) + } else if headers.contains_key(AUTHORIZATION) || body.client_secret.is_some() { + Err(invalid_request( + "Clients must authenticate only with a client assertion", + )) + } else { + body.client_assertion + .as_deref() + .ok_or_else(|| invalid_request("Missing client_assertion")) + } +} + +#[instrument(skip(rqctx, body), err(Debug))] +pub async fn client_credentials_token_op( + rqctx: &RequestContext>, + body: TypedBody, +) -> Result>, OAuthErrorResponse> +where + T: VAppPermission + PermissionStorage, +{ + Ok(token_response( + client_credentials_token_inner(rqctx.v_ctx(), rqctx.request.headers(), body.into_inner()) + .await?, + )) +} + +/// Issues a service account token to a client that authenticates with a signed assertion. +pub async fn client_credentials_token_inner( + ctx: &VContext, + headers: &http::HeaderMap, + body: ClientCredentialsTokenBody, +) -> Result, OAuthErrorResponse> +where + T: VAppPermission + PermissionStorage, +{ + let assertion = client_assertion(headers, &body)?; + let scope = requested_scope::(body.scope.as_deref())?; + + let registration_user = ctx.builtin_registration_user(); + let client = ctx + .oauth + .authenticate_client( + ®istration_user, + assertion, + body.client_id.as_ref(), + &ctx.client_assertion_policy(), + ) + .await + .map_err(|err| match err { + ClientAuthenticationError::Storage(err) => { + tracing::error!(?err, "Failed to authenticate client"); + OAuthErrorResponse::new(OAuthErrorCode::ServerError, None) + } + ClientAuthenticationError::Restricted => { + tracing::error!("Registration user is not allowed to authenticate clients"); + OAuthErrorResponse::new(OAuthErrorCode::ServerError, None) + } + ClientAuthenticationError::ClientMismatch => { + tracing::info!("Refused client assertion for a different client"); + invalid_client("client_id does not match the client that issued the assertion") + } + err => { + tracing::info!(?err, "Refused client assertion"); + invalid_client("Client authentication failed") + } + })?; + + let token = ctx + .generate_service_account_token( + ®istration_user, + &client.id, + scope + .split(' ') + .filter(|scope| !scope.is_empty()) + .map(|scope| scope.to_string()) + .collect(), + ) + .await + .map_err(HttpError::from)?; + + Ok(HttpResponseOk(ClientCredentialsTokenResponse { + access_token: token.signed_token, + token_type: "Bearer".to_string(), + expires_in: token.expires_in, + scope, + })) +} + +#[cfg(test)] +mod tests { + use chrono::Utc; + use dropshot::HttpResponseError; + use http::{HeaderMap, HeaderValue, StatusCode, header::AUTHORIZATION}; + use newtype_uuid::TypedUuid; + use serde_json::json; + use std::{ + collections::HashSet, + sync::{Arc, Mutex}, + }; + use v_model::{ + OAuthClient, OAuthClientAssertion, OAuthClientId, OAuthClientKey, ServiceAccount, + ServiceAccountToken, + permissions::Principal, + storage::{ + MockOAuthClientAssertionStore, MockOAuthClientKeyStore, MockOAuthClientStore, + MockServiceAccountStore, MockServiceAccountTokenStore, StoreError, + }, + }; + + use super::{ + ClientCredentialsTokenBody, JWT_BEARER_ASSERTION_TYPE, OAuthErrorResponse, + client_credentials_token_inner, + }; + use crate::{ + VContext, + authn::{ + AuthToken, + client_assertion::tests::{TestKey, claims, header}, + client_key::JwkThumbprint, + jwt::{Jwt, TokenClaims}, + }, + context::test_mocks::{MockStorage, mock_context}, + permissions::VPermission, + secrets::OpenApiSecretString, + }; + + /// What the token endpoint wrote to storage + #[derive(Default)] + struct Recorded { + assertions: HashSet, + tokens: Vec, + } + + /// A key pair registered to a client + struct RegisteredKey { + client_id: TypedUuid, + key: TestKey, + kid: String, + } + + impl RegisteredKey { + fn new(client_id: TypedUuid) -> Self { + let key = TestKey::new(); + let kid = key.public_jwk().thumbprint().unwrap(); + Self { + client_id, + key, + kid, + } + } + + fn stored(&self) -> OAuthClientKey { + OAuthClientKey { + id: TypedUuid::new_v4(), + oauth_client_id: self.client_id, + thumbprint: self.kid.clone(), + jwk: self.key.public_jwk(), + created_at: Utc::now(), + deleted_at: None, + } + } + + /// A valid assertion signed with this key that names `issuer` as the client + fn assertion_for(&self, issuer: TypedUuid) -> String { + self.key.assertion(issuer, &self.kid) + } + } + + struct Fixture { + ctx: VContext, + client_id: TypedUuid, + key: RegisteredKey, + /// A key registered to a different client that also exists + other: RegisteredKey, + /// A key registered to a client that has been deleted + orphan: RegisteredKey, + recorded: Arc>, + } + + /// A context holding the client under test and a second live client, each with one + /// registered key, along with a key left behind by a deleted client. The service account of + /// every live client holds `CreateGroup` and `GetMappersAll`. + async fn fixture() -> Fixture { + let client_id = TypedUuid::new_v4(); + let other_client_id = TypedUuid::new_v4(); + let key = RegisteredKey::new(client_id); + let other = RegisteredKey::new(other_client_id); + let orphan = RegisteredKey::new(TypedUuid::new_v4()); + let recorded = Arc::new(Mutex::new(Recorded::default())); + + let stored_keys = vec![key.stored(), other.stored(), orphan.stored()]; + let mut key_store = MockOAuthClientKeyStore::new(); + let listed = stored_keys.clone(); + key_store.expect_list().returning(move |filter, _| { + let thumbprints = filter.thumbprint.unwrap_or_default(); + Ok(listed + .iter() + .filter(|key| thumbprints.contains(&key.thumbprint)) + .cloned() + .collect()) + }); + + // Deleted clients are filtered out by the lookup, so only the live clients are found + let mut client_store = MockOAuthClientStore::new(); + client_store.expect_get().returning(move |id, deleted| { + Ok( + ([client_id, other_client_id].contains(id) && !deleted).then(|| OAuthClient { + id: *id, + secrets: vec![], + redirect_uris: vec![], + keys: stored_keys + .iter() + .filter(|key| &key.oauth_client_id == id) + .cloned() + .collect(), + created_at: Utc::now(), + deleted_at: None, + }), + ) + }); + + let mut assertion_store = MockOAuthClientAssertionStore::new(); + let assertions = recorded.clone(); + assertion_store.expect_record().returning(move |assertion| { + if assertions + .lock() + .unwrap() + .assertions + .insert(assertion.jti.clone()) + { + Ok(OAuthClientAssertion { + oauth_client_id: assertion.oauth_client_id, + jti: assertion.jti, + expires_at: assertion.expires_at, + created_at: Utc::now(), + }) + } else { + Err(StoreError::Conflict) + } + }); + + let mut token_store = MockServiceAccountTokenStore::new(); + let created = recorded.clone(); + token_store.expect_create().returning(move |token| { + let token = ServiceAccountToken { + id: token.id, + oauth_client_id: token.oauth_client_id, + expires_at: token.expires_at, + revoked_at: None, + created_at: Utc::now(), + updated_at: Utc::now(), + }; + created.lock().unwrap().tokens.push(token.clone()); + Ok(token) + }); + let known = recorded.clone(); + token_store.expect_get().returning(move |id, _| { + Ok(known + .lock() + .unwrap() + .tokens + .iter() + .find(|token| &token.id == id) + .cloned()) + }); + + let mut account_store = MockServiceAccountStore::new(); + account_store.expect_get().returning(|id| { + Ok(Some(ServiceAccount { + id: *id, + permissions: vec![VPermission::CreateGroup, VPermission::GetMappersAll].into(), + created_at: Utc::now(), + updated_at: Utc::now(), + generation: 0, + })) + }); + + let mut storage = MockStorage::new(); + storage.oauth_client_store = Some(Arc::new(client_store)); + storage.oauth_client_key_store = Some(Arc::new(key_store)); + storage.oauth_client_assertion_store = Some(Arc::new(assertion_store)); + storage.service_account_token_store = Some(Arc::new(token_store)); + storage.service_account_store = Some(Arc::new(account_store)); + + Fixture { + ctx: mock_context(Arc::new(storage)).await, + client_id, + key, + other, + orphan, + recorded, + } + } + + /// A well formed request from `client_id` carrying `assertion` + fn request_from( + client_id: TypedUuid, + assertion: String, + scope: Option<&str>, + ) -> ClientCredentialsTokenBody { + ClientCredentialsTokenBody { + grant_type: "client_credentials".to_string(), + scope: scope.map(|scope| scope.to_string()), + client_assertion_type: Some(JWT_BEARER_ASSERTION_TYPE.to_string()), + client_assertion: Some(assertion), + client_id: Some(client_id), + client_secret: None, + } + } + + fn no_headers() -> HeaderMap { + HeaderMap::new() + } + + fn basic_auth() -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert( + AUTHORIZATION, + HeaderValue::from_static("Basic Y2xpZW50OnNlY3JldA=="), + ); + headers + } + + /// The `error` member of the response body a failed request is answered with + fn error_code(result: &Result) -> String { + let err = result.as_ref().err().expect("expected the request to fail"); + serde_json::to_value(err).unwrap()["error"] + .as_str() + .unwrap() + .to_string() + } + + fn get_status(result: &Result) -> StatusCode { + match result { + Ok(_) => StatusCode::OK, + Err(err) => err.status_code().as_status(), + } + } + + impl Fixture { + fn assertion(&self) -> String { + self.key.assertion_for(self.client_id) + } + + /// A well formed request from the client under test carrying `assertion` + fn request(&self, assertion: String, scope: Option<&str>) -> ClientCredentialsTokenBody { + request_from(self.client_id, assertion, scope) + } + + fn recorded_assertions(&self) -> usize { + self.recorded.lock().unwrap().assertions.len() + } + } + + /// A valid assertion is exchanged for a service account token, which then resolves to the + /// client's service account narrowed by the requested scope + #[tokio::test] + async fn issues_a_service_account_token() { + let fixture = fixture().await; + + let response = client_credentials_token_inner( + &fixture.ctx, + &no_headers(), + fixture.request(fixture.assertion(), Some("group:info:w")), + ) + .await + .unwrap() + .0; + assert_eq!("Bearer", response.token_type); + assert_eq!("group:info:w", response.scope); + assert!(response.expires_in > 0); + + let token: AuthToken = Jwt::::new(&fixture.ctx, &response.access_token) + .await + .unwrap() + .into(); + let caller = fixture + .ctx + .get_caller_from_token(Some(&token)) + .await + .unwrap(); + + assert_eq!( + Principal::ServiceAccount(fixture.client_id), + caller.principal + ); + assert_eq!( + v_model::Permissions::from(vec![VPermission::CreateGroup]), + caller.permissions + ); + assert_eq!(1, fixture.recorded.lock().unwrap().tokens.len()); + } + + /// An assertion is accepted once + #[tokio::test] + async fn refuses_a_replayed_assertion() { + let fixture = fixture().await; + let assertion = fixture.assertion(); + + let first = client_credentials_token_inner( + &fixture.ctx, + &no_headers(), + fixture.request(assertion.clone(), None), + ) + .await; + assert_eq!(StatusCode::OK, get_status(&first)); + + let replay = client_credentials_token_inner( + &fixture.ctx, + &no_headers(), + fixture.request(assertion, None), + ) + .await; + assert_eq!(StatusCode::UNAUTHORIZED, get_status(&replay)); + assert_eq!("invalid_client", error_code(&replay)); + assert_eq!(1, fixture.recorded.lock().unwrap().tokens.len()); + } + + /// Requests that are malformed are refused before the assertion is verified, so they never + /// take up its jti + #[tokio::test] + async fn refuses_malformed_requests_without_using_the_assertion() { + let fixture = fixture().await; + + let cases: Vec<(&str, HeaderMap, ClientCredentialsTokenBody)> = vec![ + ( + "unsupported_grant_type", + no_headers(), + ClientCredentialsTokenBody { + grant_type: "authorization_code".to_string(), + ..fixture.request(fixture.assertion(), None) + }, + ), + ( + "invalid_request", + no_headers(), + ClientCredentialsTokenBody { + client_assertion_type: None, + ..fixture.request(fixture.assertion(), None) + }, + ), + ( + "invalid_request", + no_headers(), + ClientCredentialsTokenBody { + client_assertion_type: Some( + "urn:ietf:params:oauth:client-assertion-type:saml2-bearer".to_string(), + ), + ..fixture.request(fixture.assertion(), None) + }, + ), + ( + "invalid_request", + no_headers(), + ClientCredentialsTokenBody { + client_assertion: None, + ..fixture.request(fixture.assertion(), None) + }, + ), + ( + "invalid_request", + basic_auth(), + fixture.request(fixture.assertion(), None), + ), + ( + "invalid_request", + no_headers(), + ClientCredentialsTokenBody { + client_secret: Some(OpenApiSecretString("secret".to_string().into())), + ..fixture.request(fixture.assertion(), None) + }, + ), + ( + "invalid_scope", + no_headers(), + fixture.request(fixture.assertion(), Some("not-a-scope")), + ), + ]; + + for (expected, headers, body) in cases { + let result = client_credentials_token_inner(&fixture.ctx, &headers, body).await; + assert_eq!(StatusCode::BAD_REQUEST, get_status(&result), "{expected}"); + assert_eq!(expected, error_code(&result)); + } + + assert_eq!(0, fixture.recorded_assertions()); + } + + /// Assertions that fail authentication are refused as invalid_client, and an assertion that + /// fails verification never takes up its jti + #[tokio::test] + async fn refuses_assertions_that_fail_authentication() { + let fixture = fixture().await; + let kid = &fixture.key.kid; + + let requests = [ + // A key left behind by a client that has been deleted + request_from( + fixture.orphan.client_id, + fixture.orphan.assertion_for(fixture.orphan.client_id), + None, + ), + // A kid that no client holds + fixture.request( + fixture.key.key.assertion(fixture.client_id, "unknown-kid"), + None, + ), + // Signed by a key that is not registered under the kid + fixture.request(TestKey::new().assertion(fixture.client_id, kid), None), + // An audience other than v-api + fixture.request( + fixture.key.key.sign(&header(kid), &{ + let mut claims = claims(fixture.client_id); + claims["aud"] = json!("https://elsewhere"); + claims + }), + None, + ), + ]; + + for body in requests { + let result = client_credentials_token_inner(&fixture.ctx, &no_headers(), body).await; + assert_eq!(StatusCode::UNAUTHORIZED, get_status(&result)); + assert_eq!("invalid_client", error_code(&result)); + } + + assert_eq!(0, fixture.recorded_assertions()); + assert!(fixture.recorded.lock().unwrap().tokens.is_empty()); + } + + /// A client_id in the request is optional, as RFC 7521 §4.2 allows when the client + /// authenticates with an assertion. When it is present it must name the client that issued + /// the assertion, and a request naming another client is refused without issuing a token. + #[tokio::test] + async fn a_client_id_must_match_the_assertion_when_present() { + let fixture = fixture().await; + let assertion = fixture.assertion(); + + let mismatched = client_credentials_token_inner( + &fixture.ctx, + &no_headers(), + ClientCredentialsTokenBody { + client_id: Some(TypedUuid::new_v4()), + ..fixture.request(assertion.clone(), None) + }, + ) + .await; + assert_eq!(StatusCode::UNAUTHORIZED, get_status(&mismatched)); + assert_eq!("invalid_client", error_code(&mismatched)); + assert!(fixture.recorded.lock().unwrap().tokens.is_empty()); + assert_eq!( + 0, + fixture.recorded_assertions(), + "a refused request must not consume the assertion" + ); + + // The same assertion is still usable once the request names the right client + let corrected = client_credentials_token_inner( + &fixture.ctx, + &no_headers(), + ClientCredentialsTokenBody { + client_id: Some(fixture.client_id), + ..fixture.request(assertion, None) + }, + ) + .await; + assert_eq!(StatusCode::OK, get_status(&corrected)); + + let without_client_id = client_credentials_token_inner( + &fixture.ctx, + &no_headers(), + ClientCredentialsTokenBody { + client_id: None, + ..fixture.request(fixture.assertion(), None) + }, + ) + .await; + assert_eq!(StatusCode::OK, get_status(&without_client_id)); + assert_eq!(2, fixture.recorded.lock().unwrap().tokens.len()); + } + + /// A client can never act as another client. An assertion signed with one client's key that + /// names a different client is refused even though its signature is valid, whichever client + /// the request claims to come from. + #[tokio::test] + async fn refuses_an_assertion_signed_by_another_clients_key() { + let fixture = fixture().await; + let impersonation = fixture.other.assertion_for(fixture.client_id); + + for client_id in [fixture.client_id, fixture.other.client_id] { + let result = client_credentials_token_inner( + &fixture.ctx, + &no_headers(), + request_from(client_id, impersonation.clone(), Some("full")), + ) + .await; + assert_eq!( + StatusCode::UNAUTHORIZED, + get_status(&result), + "{client_id:?}" + ); + assert_eq!("invalid_client", error_code(&result)); + } + + assert_eq!(0, fixture.recorded_assertions()); + assert!(fixture.recorded.lock().unwrap().tokens.is_empty()); + } +} diff --git a/v-api/src/endpoints/login/oauth/flow/code.rs b/v-api/src/endpoints/login/oauth/flow/code.rs index 3852eae3..8f5000f4 100644 --- a/v-api/src/endpoints/login/oauth/flow/code.rs +++ b/v-api/src/endpoints/login/oauth/flow/code.rs @@ -6,7 +6,7 @@ use base64::{Engine, prelude::BASE64_URL_SAFE_NO_PAD}; use chrono::{TimeDelta, Utc}; use cookie::{Cookie, SameSite}; use dropshot::{ - ClientErrorStatusCode, HttpError, HttpResponseOk, HttpResponseTemporaryRedirect, Path, Query, + HttpError, HttpResponseHeaders, HttpResponseOk, HttpResponseTemporaryRedirect, Path, Query, RequestContext, RequestInfo, SharedExtractor, TypedBody, http_response_temporary_redirect, }; use dropshot_authorization_header::basic::BasicAuth; @@ -30,7 +30,8 @@ use v_model::{ }; use super::super::{OAuthProvider, OAuthProviderNameParam}; -use super::UpstreamTokens; +use super::error::{OAuthErrorCode, OAuthErrorResponse}; +use super::{UpstreamTokens, requested_scope, token_response}; use crate::endpoints::login::UserInfoProvider; use crate::{ authn::key::RawKey, @@ -102,57 +103,6 @@ fn login_attempt_clear_cookies(public_url: &str) -> Result, Htt .collect() } -// RFC 6749 §5.2 shaped error -#[derive(Debug, Deserialize, JsonSchema, Serialize, PartialEq, Eq)] -struct OAuthError { - error: OAuthErrorCode, - #[serde(skip_serializing_if = "Option::is_none")] - error_description: Option, - #[serde(skip_serializing_if = "Option::is_none")] - error_uri: Option, - #[serde(skip_serializing_if = "Option::is_none")] - state: Option, -} - -impl OAuthError { - pub fn new(error: OAuthErrorCode, error_description: Option<&str>) -> Self { - Self { - error, - error_description: error_description.map(|s| s.to_string()), - error_uri: None, - state: None, - } - } -} - -#[derive(Debug, Deserialize, JsonSchema, Serialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum OAuthErrorCode { - AccessDenied, - InvalidClient, - InvalidGrant, - InvalidRequest, - InvalidScope, - ServerError, - TemporarilyUnavailable, - UnauthorizedClient, - UnsupportedGrantType, - UnsupportedResponseType, -} - -impl From for HttpError { - fn from(value: OAuthError) -> Self { - let serialized = serde_json::to_string(&value).unwrap(); - HttpError { - headers: None, - status_code: ClientErrorStatusCode::BAD_REQUEST.into(), - error_code: None, - external_message: serialized.clone(), - internal_message: serialized, - } - } -} - #[derive(Debug, Deserialize, JsonSchema, Serialize)] pub struct OAuthAuthzCodeQuery { pub client_id: TypedUuid, @@ -160,7 +110,7 @@ pub struct OAuthAuthzCodeQuery { pub response_type: String, pub state: String, pub scope: Option, - /// PKCE code challenge (RFC 7636). Required for all authorization code flows. + /// PKCE code challenge (RFC 7636 §4.2). Required for all authorization code flows. pub code_challenge: String, /// PKCE code challenge method. Must be "S256". pub code_challenge_method: String, @@ -176,41 +126,87 @@ pub struct OAuthAuthzCodeRedirectHeaders { /// Validate the PKCE code challenge. For S256, this must be a base64url-no-pad /// encoding of a SHA256 hash, which is always exactly 43 characters of [A-Za-z0-9_-] /// (RFC 7636 §4.2). -fn validate_code_challenge(code_challenge: &str) -> Result<(), OAuthError> { +fn validate_code_challenge(code_challenge: &str) -> Result<&str, OAuthErrorResponse> { if !BASE64_URL_SAFE_NO_PAD .decode(code_challenge) .is_ok_and(|bytes| bytes.len() == 32) { - Err(OAuthError::new( + Err(OAuthErrorResponse::new( OAuthErrorCode::InvalidRequest, Some( "Invalid code_challenge. Must be a base64url-encoded SHA256 hash (43 characters).", ), )) } else { - Ok(()) + Ok(code_challenge) + } +} + +/// Validate that the PKCE challenge method is S256. The plain method is never accepted. +fn validate_code_challenge_method(method: &str) -> Result<&str, OAuthErrorResponse> { + if method == "S256" { + Ok(method) + } else { + Err(OAuthErrorResponse::new( + OAuthErrorCode::InvalidRequest, + Some("Unsupported code_challenge_method. Only S256 is supported."), + )) } } /// Validate that response_type is "code" per RFC 6749 §4.1.1. -fn validate_response_type(response_type: &str) -> Result<(), OAuthError> { +fn validate_response_type(response_type: &str) -> Result<(), OAuthErrorResponse> { if response_type == "code" { Ok(()) } else { - Err(OAuthError::new( + Err(OAuthErrorResponse::new( OAuthErrorCode::UnsupportedResponseType, Some("Only response_type=code is supported"), )) } } +/// An authorization request that has passed every check that does not depend on stored state +struct AuthorizationRequest { + redirect_uri: String, + state: String, + scope: String, + code_challenge: String, + code_challenge_method: String, +} + +impl AuthorizationRequest { + /// Checks an authorization request. Only response_type=code is supported (RFC 6749 §4.1.1), + /// PKCE is required with the S256 method (RFC 7636 §4.2), and the scope must parse. An absent + /// scope means no permissions, and the special scope "full" asks for all of them. + fn parse(query: OAuthAuthzCodeQuery) -> Result + where + T: VAppPermission, + { + validate_response_type(&query.response_type).and_then(|()| { + let code_challenge_method = + validate_code_challenge_method(&query.code_challenge_method)?.to_string(); + let code_challenge = validate_code_challenge(&query.code_challenge)?.to_string(); + let scope = requested_scope::(query.scope.as_deref())?; + + Ok(Self { + redirect_uri: query.redirect_uri, + state: query.state, + scope, + code_challenge, + code_challenge_method, + }) + }) + } +} + // Lookup the client specified by the provided client id and verify that the redirect uri // is a valid for this client. If either of these fail we return an unauthorized response async fn get_oauth_client( ctx: &VContext, client_id: &TypedUuid, redirect_uri: &str, -) -> Result +) -> Result where T: VAppPermission + PermissionStorage, { @@ -222,19 +218,20 @@ where tracing::error!(?err, "Failed to lookup OAuth client"); match err { - ResourceError::DoesNotExist => { - OAuthError::new(OAuthErrorCode::InvalidClient, Some("Unknown client id")) - } + ResourceError::DoesNotExist => OAuthErrorResponse::new( + OAuthErrorCode::InvalidClient, + Some("Unknown client id"), + ), // Given that the builtin caller should have access to all OAuth clients, any other // error is considered an internal error - _ => OAuthError::new(OAuthErrorCode::ServerError, None), + _ => OAuthErrorResponse::new(OAuthErrorCode::ServerError, None), } })?; if client.is_redirect_uri_valid(redirect_uri) { Ok(client) } else { - Err(OAuthError::new( + Err(OAuthErrorResponse::new( OAuthErrorCode::InvalidRequest, Some("Invalid redirect uri"), )) @@ -272,7 +269,7 @@ pub async fn authz_code_redirect_op( rqctx: &RequestContext>, path: Path, query: Query, -) -> Result +) -> Result where T: VAppPermission + PermissionStorage, { @@ -280,23 +277,11 @@ where let path = path.into_inner(); let query = query.into_inner(); - get_oauth_client(ctx, &query.client_id, &query.redirect_uri).await?; + let client = get_oauth_client(ctx, &query.client_id, &query.redirect_uri).await?; - tracing::debug!(?query.client_id, ?query.redirect_uri, "Verified client id and redirect uri"); + tracing::debug!(?client.id, ?query.redirect_uri, "Verified client id and redirect uri"); - // Validate response_type. Only "code" is supported (RFC 6749 §4.1.1). - validate_response_type(&query.response_type)?; - - // Validate the client's PKCE challenge method. Only S256 is supported. - if query.code_challenge_method != "S256" { - Err(OAuthError::new( - OAuthErrorCode::InvalidRequest, - Some("Unsupported code_challenge_method. Only S256 is supported."), - ))?; - } - - // Validate the PKCE code challenge (RFC 7636 §4.2). - validate_code_challenge(&query.code_challenge)?; + let request = AuthorizationRequest::parse::(query)?; // Find the configured provider for the requested remote backend. We should always have a valid // provider value, so if this fails then a 500 is returned @@ -307,24 +292,12 @@ where tracing::debug!(provider = ?provider.name(), "Acquired OAuth provider for authz code login"); - // Check that the passed in scopes are valid. A None scope means no permissions. - // Use the special scope "full" to request all permissions. - if let Some(ref scope) = query.scope - && let Err(err) = T::from_scope_arg(scope) - { - tracing::warn!(?err, ?scope, "Client submitted an invalid scope"); - Err(OAuthError::new( - OAuthErrorCode::InvalidScope, - Some(format!("Invalid scope: {}", scope).as_str()), - ))?; - } - // Construct a new login attempt with the minimum required values let mut attempt = NewLoginAttempt::new( provider.name().to_string(), - query.client_id, - Some(query.redirect_uri), - query.scope.unwrap_or_default(), + client.id, + Some(request.redirect_uri), + request.scope, "authorization_code".to_string(), ) .map_err(|err| { @@ -339,12 +312,12 @@ where // Store the client's state value as-is. Per RFC 6749 §4.1.1, the authorization server // MUST return the state parameter unmodified. The value will be properly percent-encoded // when it is placed into the redirect URL by `callback_url()` via `append_pair`. - attempt.state = Some(query.state); + attempt.state = Some(request.state); // Always store the client's PKCE challenge so we can verify it during the token exchange. // This is the client-to-v-api PKCE leg and is mandatory for all flows. - attempt.pkce_challenge = Some(query.code_challenge); - attempt.pkce_challenge_method = Some(query.code_challenge_method); + attempt.pkce_challenge = Some(request.code_challenge); + attempt.pkce_challenge_method = Some(request.code_challenge_method); // If the remote provider supports PKCE, also set up a challenge for the v-api-to-remote leg. // This is independent of the client-to-v-api PKCE above. @@ -365,12 +338,12 @@ where tracing::info!(?attempt.id, "Created login attempt"); - oauth_redirect_response( + Ok(oauth_redirect_response( ctx.public_url(), &*provider, &attempt, remote_pkce_challenge, - ) + )?) } fn oauth_redirect_response( @@ -481,7 +454,9 @@ pub struct OAuthAuthzCodeReturnQuery { pub error: Option, } -#[instrument(skip(rqctx), err(Debug))] +// The query carries the authorization code the upstream provider issued, which must not be +// recorded in the request span +#[instrument(skip(rqctx, query), err(Debug))] pub async fn authz_code_callback_op( rqctx: &RequestContext>, path: Path, @@ -645,7 +620,7 @@ pub struct OAuthAuthzCodeExchangeBody { pub redirect_uri: String, pub grant_type: String, pub code: String, - /// PKCE code verifier (RFC 7636). Required for all authorization code exchanges. + /// PKCE code verifier (RFC 7636 §4.1). Required for all authorization code exchanges. pub code_verifier: String, } @@ -678,7 +653,7 @@ pub async fn authz_code_exchange_op( query: Query, path: Path, body: TypedBody, -) -> Result, HttpError> +) -> Result>, OAuthErrorResponse> where T: VAppPermission + PermissionStorage, { @@ -739,7 +714,7 @@ where Some(OpenApiSecretString(SecretString::from(client_secret))), )), (None, (Some(client_id), Some(client_secret))) => Ok((client_id, Some(client_secret))), - (None, (Some(client_id), _)) if provider.authz_code_pkce_flow_info().is_some() => { + (None, (Some(client_id), _)) if is_public_client(&*provider, &client_id) => { Ok((client_id, None)) } _ => Err(bad_request("Missing client credentials")), @@ -747,8 +722,8 @@ where tracing::debug!("Attempting code exchange"); - // Verify the submitted client credentials - authorize_code_exchange( + // Authenticate the client from the submitted credentials + let client = authorize_code_exchange( ctx, &*provider, &body.grant_type, @@ -760,22 +735,23 @@ where tracing::debug!("Authorized code exchange"); - // Lookup the request assigned to this code - let mut attempt = ctx + // Lookup the request assigned to this code, which must be valid and must match the client + // that authenticated + let attempt = ctx .login .get_login_attempt_for_code(&body.code, &provider.name().to_string()) .await .map_err(to_internal_error)? - .ok_or(OAuthError::new(OAuthErrorCode::InvalidGrant, None))?; - - // Verify that the login attempt is valid and matches the submitted client credentials - verify_login_attempt( - &attempt, - &provider.name().to_string(), - client_id, - &body.redirect_uri, - &body.code_verifier, - )?; + .ok_or(OAuthErrorResponse::new(OAuthErrorCode::InvalidGrant, None)) + .and_then(|attempt| { + verify_login_attempt( + attempt, + &provider.name().to_string(), + client.id, + &body.redirect_uri, + &body.code_verifier, + ) + })?; tracing::debug!("Verified login attempt"); @@ -784,7 +760,7 @@ where // ensuring that a concurrent request using the same authorization code will fail. // Per RFC 6749 §4.1.2, authorization codes MUST be single-use. let attempt_id = attempt.id; - attempt = ctx + let attempt = ctx .login .claim_login_attempt(attempt) .await @@ -794,7 +770,7 @@ where ?attempt_id, "Failed to claim login attempt (may have been consumed by a concurrent request)" ); - OAuthError::new( + OAuthErrorResponse::new( OAuthErrorCode::InvalidGrant, Some("Authorization code has already been used"), ) @@ -810,17 +786,24 @@ where tracing::debug!("Retrieved user information from remote provider"); - super::complete_exchange( - ctx, - info, - &*provider, - &attempt, - query.request_idp_token, - upstream, - ) - .await + Ok(token_response( + super::complete_exchange( + ctx, + info, + &*provider, + &attempt, + query.request_idp_token, + upstream, + ) + .await?, + )) } +/// The client a code exchange authenticates as. +/// +/// The exchange must ask for the authorization code grant (RFC 6749 §4.1.3). A client secret that +/// was provided must be valid. One may only be omitted by the public client the provider's PKCE +/// flow is configured with. async fn authorize_code_exchange( ctx: &VContext, provider: &dyn OAuthProvider, @@ -828,27 +811,22 @@ async fn authorize_code_exchange( client_id: TypedUuid, client_secret: Option<&SecretString>, redirect_uri: &str, -) -> Result<(), OAuthError> +) -> Result where T: VAppPermission + PermissionStorage, { let client = get_oauth_client(ctx, &client_id, redirect_uri).await?; - // Verify that we received the expected grant type if grant_type != "authorization_code" { - Err(OAuthError::new(OAuthErrorCode::UnsupportedGrantType, None))?; - } - - tracing::debug!(grant_type, "Verified grant type"); - - // If we were provided a client secret, then it must be verified. If a client secret was not - // provided, then we can skip this step as long as the provider supports pkce_only - // authentication. - if let Some(client_secret) = client_secret { + Err(OAuthErrorResponse::new( + OAuthErrorCode::UnsupportedGrantType, + None, + )) + } else if let Some(client_secret) = client_secret { let client_secret = RawKey::try_from(client_secret).map_err(|err| { tracing::warn!(?err, "Failed to parse OAuth client secret"); - OAuthError::new( + OAuthErrorResponse::new( OAuthErrorCode::InvalidRequest, Some("Malformed client secret"), ) @@ -857,54 +835,65 @@ where tracing::debug!("Constructed client secret"); if !client.is_secret_valid(&client_secret, ctx) { - Err(OAuthError::new( + Err(OAuthErrorResponse::new( OAuthErrorCode::InvalidClient, Some("Invalid client secret"), )) } else { tracing::debug!("Verified client secret validity"); - Ok(()) + Ok(client) } - } else if provider.authz_code_pkce_flow_info().is_some() { - Ok(()) + } else if is_public_client(provider, &client.id) { + Ok(client) } else { - Err(OAuthError::new( + Err(OAuthErrorResponse::new( OAuthErrorCode::InvalidRequest, Some("Client secret required"), )) } } +/// Verify that this client is the client that has been named as the PKCE client for the given +/// provider. +fn is_public_client(provider: &dyn OAuthProvider, client_id: &TypedUuid) -> bool { + provider + .authz_code_pkce_flow_info() + .is_some_and(|info| &info.client_id == client_id) +} + +/// The login attempt a code was issued for, provided the exchange matches it. The provider, the +/// client, and the redirect URI must all match, the attempt must be awaiting exchange and not +/// expired, and the PKCE verifier must match the challenge the client sent at authorization. fn verify_login_attempt( - attempt: &LoginAttempt, + attempt: LoginAttempt, provider: &str, client_id: TypedUuid, redirect_uri: &str, code_verifier: &str, -) -> Result<(), OAuthError> { +) -> Result { if attempt.provider != provider { - Err(OAuthError::new( + Err(OAuthErrorResponse::new( OAuthErrorCode::InvalidGrant, Some("Provider mismatch"), )) } else if attempt.client_id != client_id { - Err(OAuthError::new( + Err(OAuthErrorResponse::new( OAuthErrorCode::InvalidGrant, Some("Invalid client id"), )) } else if attempt.redirect_uri.as_deref() != Some(redirect_uri) { - Err(OAuthError::new( + Err(OAuthErrorResponse::new( OAuthErrorCode::InvalidGrant, Some("Invalid redirect uri"), )) } else if attempt.attempt_state != LoginAttemptState::RemoteAuthenticated { - Err(OAuthError::new( + Err(OAuthErrorResponse::new( OAuthErrorCode::InvalidGrant, Some("Grant is in an invalid state"), )) } else if attempt.expires_at.map(|t| t <= Utc::now()).unwrap_or(true) { - Err(OAuthError::new( + Err(OAuthErrorResponse::new( OAuthErrorCode::InvalidGrant, Some("Grant has expired"), )) @@ -917,9 +906,9 @@ fn verify_login_attempt( let computed_challenge = BASE64_URL_SAFE_NO_PAD.encode(hash); if challenge == computed_challenge { - Ok(()) + Ok(attempt) } else { - Err(OAuthError::new( + Err(OAuthErrorResponse::new( OAuthErrorCode::InvalidGrant, Some("Invalid pkce verifier"), )) @@ -927,7 +916,7 @@ fn verify_login_attempt( } // PKCE is mandatory for all authorization code flows. A missing challenge // means the login attempt was not properly initialized. - None => Err(OAuthError::new( + None => Err(OAuthErrorResponse::new( OAuthErrorCode::InvalidGrant, Some("Login attempt is missing a PKCE challenge"), )), @@ -1016,7 +1005,7 @@ mod tests { use uuid::Uuid; use v_model::{ AccessToken, ApiUser, ApiUserInfo, ApiUserProvider, LoginAttempt, NewApiUser, - NewApiUserProvider, OAuthClient, OAuthClientRedirectUri, OAuthClientSecret, + NewApiUserProvider, OAuthClient, OAuthClientId, OAuthClientRedirectUri, OAuthClientSecret, schema_ext::LoginAttemptState, storage::{ MockAccessGroupStore, MockAccessTokenStore, MockApiUserProviderStore, MockApiUserStore, @@ -1026,7 +1015,7 @@ mod tests { use crate::{ authn::{ - jwt::{Claims, Jwt}, + jwt::{Jwt, UserClaims}, key::RawKey, }, context::{ @@ -1036,11 +1025,11 @@ mod tests { endpoints::login::{ ExternalUserId, UserInfo, oauth::{ - OAuthProviderName, + OAuthProvider, OAuthProviderName, flow::{ code::{ - LOGIN_ATTEMPT_COOKIE, OAuthAuthzCodeReturnQuery, OAuthError, - OAuthErrorCode, authz_code_callback_op_inner, verify_csrf, + LOGIN_ATTEMPT_COOKIE, OAuthAuthzCodeReturnQuery, OAuthErrorCode, + OAuthErrorResponse, authz_code_callback_op_inner, verify_csrf, verify_login_attempt, }, should_provide_idp_token, @@ -1133,6 +1122,7 @@ mod tests { .returning(move |_, _| { Ok(Some(OAuthClient { id: client_id, + keys: vec![], secrets: vec![], redirect_uris: vec![OAuthClientRedirectUri { id: TypedUuid::new_v4(), @@ -1163,6 +1153,7 @@ mod tests { ctx, OAuthClient { id: client_id, + keys: vec![], secrets: vec![OAuthClientSecret { id: TypedUuid::new_v4(), oauth_client_id: client_id, @@ -1189,6 +1180,7 @@ mod tests { let client_id = TypedUuid::new_v4(); let client = OAuthClient { id: client_id, + keys: vec![], secrets: vec![], redirect_uris: vec![OAuthClientRedirectUri { id: TypedUuid::new_v4(), @@ -1691,7 +1683,7 @@ mod tests { // 3. Verify a successful exchange with a client secret assert_eq!( - (), + client_id, authorize_code_exchange( &ctx, &*provider, @@ -1702,66 +1694,92 @@ mod tests { ) .await .unwrap() + .id ); } + /// Only the public client a provider's PKCE flow is configured with may exchange a code + /// without a secret. A confidential client on the same provider still needs its secret. #[tokio::test] - async fn test_exchange_requires_secret_except_for_pkce_only() { + async fn test_exchange_requires_secret_except_for_the_public_client() { let (mut ctx, client, _) = mock_client().await; let client_id = client.id; let redirect_uri = client.redirect_uris[0].redirect_uri.clone(); + let provider = ctx + .get_oauth_provider(&OAuthProviderName::Google) + .await + .unwrap(); + + // The provider factory picks a fresh proxy client id each time it runs, so this instance + // is kept for both reading the id and performing the exchanges + let pkce_provider = ctx + .get_oauth_provider(&OAuthProviderName::Zendesk) + .await + .unwrap(); + let public_client_id = pkce_provider.authz_code_pkce_flow_info().unwrap().client_id; + let public_client = OAuthClient { + id: public_client_id, + ..client.clone() + }; + let mut client_store = MockOAuthClientStore::new(); client_store .expect_get() .with(eq(client_id), eq(false)) .returning(move |_, _| Ok(Some(client.clone()))); + client_store + .expect_get() + .with(eq(public_client_id), eq(false)) + .returning(move |_, _| Ok(Some(public_client.clone()))); let mut storage = MockStorage::new(); storage.oauth_client_store = Some(Arc::new(client_store)); - ctx.set_storage(Arc::new(storage)); - let provider = ctx - .get_oauth_provider(&OAuthProviderName::Google) - .await - .unwrap(); - let pkce_only_provider = ctx - .get_oauth_provider(&OAuthProviderName::Zendesk) - .await - .unwrap(); - - // 1. Verify exchange fails when not passing a client secret for a client that does not - // support pkce_only - assert_eq!( - Some("Client secret required".to_string()), + async fn exchange_without_secret( + ctx: &VContext, + provider: &dyn OAuthProvider, + client_id: TypedUuid, + redirect_uri: &str, + ) -> Result { authorize_code_exchange( - &ctx, - &*provider, + ctx, + provider, "authorization_code", client_id, None, - &redirect_uri, + redirect_uri, ) .await - .unwrap_err() - .error_description + } + + // 1. A provider without a public client always requires a secret + assert_eq!( + Some("Client secret required".to_string()), + exchange_without_secret(&ctx, &*provider, client_id, &redirect_uri) + .await + .unwrap_err() + .error_description ); - // 2. Verify exchange passes when omitting the client secret for a client that does - // support pkce_only + // 2. A confidential client on a provider that has a public client still requires its + // secret. Only the configured public client is exempt. assert_eq!( - (), - authorize_code_exchange( - &ctx, - &*pkce_only_provider, - "authorization_code", - client_id, - None, - &redirect_uri, - ) - .await - .unwrap() + Some("Client secret required".to_string()), + exchange_without_secret(&ctx, &*pkce_provider, client_id, &redirect_uri) + .await + .unwrap_err() + .error_description + ); + + // 3. The configured public client may omit its secret + assert_eq!( + public_client_id, + exchange_without_secret(&ctx, &*pkce_provider, public_client_id, &redirect_uri) + .await + .unwrap() + .id ); } @@ -1802,7 +1820,7 @@ mod tests { ); assert_eq!( - (), + client_id, authorize_code_exchange( &ctx, &*provider, @@ -1813,6 +1831,7 @@ mod tests { ) .await .unwrap() + .id ); } @@ -1875,7 +1894,7 @@ mod tests { ); assert_eq!( - (), + client_id, authorize_code_exchange( &ctx, &*provider, @@ -1886,6 +1905,7 @@ mod tests { ) .await .unwrap() + .id ); } @@ -1921,14 +1941,9 @@ mod tests { }; assert_eq!( - OAuthError { - error: OAuthErrorCode::InvalidGrant, - error_description: Some("Invalid client id".to_string()), - error_uri: None, - state: None, - }, + OAuthErrorResponse::new(OAuthErrorCode::InvalidGrant, Some("Invalid client id")), verify_login_attempt( - &bad_client_id, + bad_client_id.clone(), &attempt.provider, attempt.client_id, attempt.redirect_uri.as_deref().unwrap(), @@ -1943,14 +1958,9 @@ mod tests { }; assert_eq!( - OAuthError { - error: OAuthErrorCode::InvalidGrant, - error_description: Some("Invalid redirect uri".to_string()), - error_uri: None, - state: None, - }, + OAuthErrorResponse::new(OAuthErrorCode::InvalidGrant, Some("Invalid redirect uri")), verify_login_attempt( - &bad_redirect_uri, + bad_redirect_uri.clone(), &attempt.provider, attempt.client_id, attempt.redirect_uri.as_deref().unwrap(), @@ -1965,14 +1975,12 @@ mod tests { }; assert_eq!( - OAuthError { - error: OAuthErrorCode::InvalidGrant, - error_description: Some("Grant is in an invalid state".to_string()), - error_uri: None, - state: None, - }, + OAuthErrorResponse::new( + OAuthErrorCode::InvalidGrant, + Some("Grant is in an invalid state") + ), verify_login_attempt( - &unconfirmed_state, + unconfirmed_state.clone(), &attempt.provider, attempt.client_id, attempt.redirect_uri.as_deref().unwrap(), @@ -1987,14 +1995,12 @@ mod tests { }; assert_eq!( - OAuthError { - error: OAuthErrorCode::InvalidGrant, - error_description: Some("Grant is in an invalid state".to_string()), - error_uri: None, - state: None, - }, + OAuthErrorResponse::new( + OAuthErrorCode::InvalidGrant, + Some("Grant is in an invalid state") + ), verify_login_attempt( - &already_used_state, + already_used_state.clone(), &attempt.provider, attempt.client_id, attempt.redirect_uri.as_deref().unwrap(), @@ -2009,14 +2015,12 @@ mod tests { }; assert_eq!( - OAuthError { - error: OAuthErrorCode::InvalidGrant, - error_description: Some("Grant is in an invalid state".to_string()), - error_uri: None, - state: None, - }, + OAuthErrorResponse::new( + OAuthErrorCode::InvalidGrant, + Some("Grant is in an invalid state") + ), verify_login_attempt( - &failed_state, + failed_state.clone(), &attempt.provider, attempt.client_id, attempt.redirect_uri.as_deref().unwrap(), @@ -2031,14 +2035,9 @@ mod tests { }; assert_eq!( - OAuthError { - error: OAuthErrorCode::InvalidGrant, - error_description: Some("Grant has expired".to_string()), - error_uri: None, - state: None, - }, + OAuthErrorResponse::new(OAuthErrorCode::InvalidGrant, Some("Grant has expired")), verify_login_attempt( - &expired, + expired.clone(), &attempt.provider, attempt.client_id, attempt.redirect_uri.as_deref().unwrap(), @@ -2056,14 +2055,12 @@ mod tests { }; assert_eq!( - OAuthError { - error: OAuthErrorCode::InvalidGrant, - error_description: Some("Login attempt is missing a PKCE challenge".to_string()), - error_uri: None, - state: None, - }, + OAuthErrorResponse::new( + OAuthErrorCode::InvalidGrant, + Some("Login attempt is missing a PKCE challenge") + ), verify_login_attempt( - &missing_challenge, + missing_challenge.clone(), &attempt.provider, attempt.client_id, attempt.redirect_uri.as_deref().unwrap(), @@ -2078,14 +2075,9 @@ mod tests { }; assert_eq!( - OAuthError { - error: OAuthErrorCode::InvalidGrant, - error_description: Some("Invalid pkce verifier".to_string()), - error_uri: None, - state: None, - }, + OAuthErrorResponse::new(OAuthErrorCode::InvalidGrant, Some("Invalid pkce verifier")), verify_login_attempt( - &invalid_pkce, + invalid_pkce.clone(), &attempt.provider, attempt.client_id, attempt.redirect_uri.as_deref().unwrap(), @@ -2095,15 +2087,16 @@ mod tests { ); assert_eq!( - (), + attempt.id, verify_login_attempt( - &attempt, + attempt.clone(), &attempt.provider, attempt.client_id, attempt.redirect_uri.as_deref().unwrap(), verifier.secret().as_str(), ) .unwrap() + .id ); } @@ -2137,14 +2130,9 @@ mod tests { // Exchanging against a different provider must fail assert_eq!( - OAuthError { - error: OAuthErrorCode::InvalidGrant, - error_description: Some("Provider mismatch".to_string()), - error_uri: None, - state: None, - }, + OAuthErrorResponse::new(OAuthErrorCode::InvalidGrant, Some("Provider mismatch")), verify_login_attempt( - &attempt, + attempt.clone(), "github", attempt.client_id, attempt.redirect_uri.as_deref().unwrap(), @@ -2155,15 +2143,16 @@ mod tests { // Exchanging against the correct provider must succeed assert_eq!( - (), + attempt.id, verify_login_attempt( - &attempt, + attempt.clone(), "google", attempt.client_id, attempt.redirect_uri.as_deref().unwrap(), verifier.secret().as_str(), ) .unwrap() + .id ); } @@ -2361,6 +2350,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }, email: None, providers: vec![], @@ -2425,10 +2415,9 @@ mod tests { }) }); - // ApiUserStore: upsert creates a user with the specified permissions let mut user_store = MockApiUserStore::new(); user_store - .expect_upsert() + .expect_create() .returning(move |u: NewApiUser| { Ok(ApiUserInfo { user: ApiUser { @@ -2438,6 +2427,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }, email: None, providers: vec![], @@ -2876,6 +2866,7 @@ mod tests { .returning(move |_, _| { Ok(Some(OAuthClient { id: client_id, + keys: vec![], secrets: vec![], redirect_uris: vec![], // No registered URIs created_at: Utc::now(), @@ -3023,7 +3014,7 @@ mod tests { "Exchange response scope must be empty when the login attempt has no scope", ); - let jwt = Jwt::::new(&ctx, &response.access_token) + let jwt = Jwt::::new(&ctx, &response.access_token) .await .expect("JWT should decode successfully"); @@ -3070,7 +3061,7 @@ mod tests { "Exchange response must echo back the full scope", ); - let jwt = Jwt::::new(&ctx, &response.access_token) + let jwt = Jwt::::new(&ctx, &response.access_token) .await .expect("JWT should decode successfully"); @@ -3117,7 +3108,7 @@ mod tests { "Exchange response must echo back the explicit scope", ); - let jwt = Jwt::::new(&ctx, &response.access_token) + let jwt = Jwt::::new(&ctx, &response.access_token) .await .expect("JWT should decode successfully"); diff --git a/v-api/src/endpoints/login/oauth/flow/device_token.rs b/v-api/src/endpoints/login/oauth/flow/device_token.rs index 705a72fb..e60bca55 100644 --- a/v-api/src/endpoints/login/oauth/flow/device_token.rs +++ b/v-api/src/endpoints/login/oauth/flow/device_token.rs @@ -11,14 +11,17 @@ use oauth2::{ CsrfToken, EmptyExtraTokenFields, StandardTokenResponse, TokenResponse, basic::BasicTokenType, }; use schemars::JsonSchema; -use secrecy::ExposeSecret; +use secrecy::{ExposeSecret, SecretString}; use serde::{Deserialize, Serialize}; use std::fmt::Debug; use std::ops::Add; use tap::TapFallible; use tracing::instrument; use url::Url; -use v_model::{NewLoginAttempt, OAuthClientId, permissions::PermissionStorage}; +use v_model::{ + LoginAttempt, NewLoginAttempt, OAuthClientId, permissions::PermissionStorage, + schema_ext::LoginAttemptState, +}; use super::super::OAuthProviderNameParam; use crate::endpoints::login::UserInfoProvider; @@ -27,9 +30,29 @@ use crate::{ permissions::VAppPermission, response::internal_error, util::response::bad_request, }; -use super::{UpstreamTokens, complete_exchange}; +use super::{ + DEVICE_CODE_GRANT_TYPE, UpstreamTokens, complete_exchange, + error::{OAuthErrorCode, OAuthErrorResponse}, + mark_uncacheable, requested_scope, revoke_upstream_tokens, +}; use crate::endpoints::login::oauth::OAuthProviderDeviceInfo; +/// Verify that this client is the client that has been named as the device client for the given +/// provider. +fn configured_device_client( + device_info: &OAuthProviderDeviceInfo, + client_id: TypedUuid, +) -> Result, OAuthErrorResponse> { + if device_info.client_id == client_id { + Ok(client_id) + } else { + Err(OAuthErrorResponse::new( + OAuthErrorCode::InvalidClient, + Some("client_id is not the provider's device client"), + )) + } +} + #[instrument(skip(rqctx), err(Debug))] pub async fn get_device_provider_op( rqctx: &RequestContext>, @@ -101,7 +124,7 @@ pub async fn device_authz_op( rqctx: &RequestContext>, path: Path, body: TypedBody, -) -> Result, HttpError> +) -> Result, OAuthErrorResponse> where T: VAppPermission + PermissionStorage, { @@ -117,25 +140,20 @@ where let device_info = provider .device_code_flow_info() .ok_or_else(|| bad_request("Provider does not support device code flow"))?; + let client_id = configured_device_client(device_info, body.client_id)?; - // Validate the client_id. In the future we may tie maximum scopes to a - // client as well - let _client = ctx + // The device client must also be a registered client. In the future we may tie maximum + // scopes to a client as well + let registered_client = ctx .oauth - .get_oauth_client(&ctx.builtin_registration_user(), &body.client_id) + .get_oauth_client(&ctx.builtin_registration_user(), &client_id) .await - .map_err(|_| bad_request("Unknown client id"))?; + .map_err(|_| { + OAuthErrorResponse::new(OAuthErrorCode::InvalidClient, Some("Unknown client id")) + })?; // An omitted scope means no permissions - let scope = body.scope.unwrap_or_default(); - if let Err(err) = T::from_scope_arg(&scope) { - tracing::warn!(?err, ?scope, "Client submitted an invalid scope"); - return Ok(error_response( - StatusCode::BAD_REQUEST, - "invalid_scope", - Some(format!("Invalid scope: {}", scope)), - )); - } + let scope = requested_scope::(body.scope.as_deref())?; // Proxy the device authorization request to the upstream provider let client = reqwest::Client::new(); @@ -188,10 +206,10 @@ where // redirect_uri — the token is returned directly via the exchange endpoint. let mut attempt = NewLoginAttempt::new( provider.name().to_string(), - body.client_id, + registered_client.id, None, scope, - "urn:ietf:params:oauth:grant-type:device_code".to_string(), + DEVICE_CODE_GRANT_TYPE.to_string(), ) .map_err(|err| { tracing::error!(?err, "Failed to construct login attempt"); @@ -283,7 +301,7 @@ pub async fn exchange_device_token_op( rqctx: &RequestContext>, path: Path, body: TypedBody, -) -> Result, HttpError> +) -> Result, OAuthErrorResponse> where T: VAppPermission + PermissionStorage, { @@ -299,49 +317,30 @@ where let device_info = provider .device_code_flow_info() .ok_or_else(|| bad_request("Provider does not support device code flow"))?; + let client_id = configured_device_client(device_info, body.client_id)?; tracing::debug!(provider = ?provider.name(), "Acquired OAuth provider for device token exchange"); - // Validate grant_type per RFC 8628 §3.4 - if !validate_device_grant_type(&body.grant_type) { - return Ok(error_response( - StatusCode::BAD_REQUEST, - "unsupported_grant_type", - Some("grant_type must be urn:ietf:params:oauth:grant-type:device_code".to_string()), - )); - } + // Only the device code grant is accepted (RFC 8628 §3.4) + let grant_type = device_grant_type(&body.grant_type)?; - // Look up the login attempt by the v-api-issued device code and client_id. + // Look up the login attempt by the v-api-issued device code and client_id. Only an attempt + // that is still open and has not expired can be exchanged. let attempt = ctx .login - .get_login_attempt_for_device_code(&body.device_code, &body.client_id) + .get_login_attempt_for_device_code(&body.device_code, &client_id) .await .map_err(|err| { tracing::error!(?err, "Failed to look up device login attempt"); internal_error("Failed to look up login attempt") })? - .ok_or_else(|| bad_request("Unknown device code or client id"))?; - - // Verify the attempt is still in the New state - if attempt.attempt_state != v_model::schema_ext::LoginAttemptState::New { - return Ok(error_response( - StatusCode::BAD_REQUEST, - "invalid_grant", - Some("Device code has already been exchanged".to_string()), - )); - } - - // Check expiration - An attempt without an expiration is by default - // expired. - // TODO: Change expires_at to be non-optional. A login attempt should always - // have an expiration. - if attempt.expires_at.map(|t| t <= Utc::now()).unwrap_or(true) { - return Ok(error_response( - StatusCode::BAD_REQUEST, - "expired_token", - Some("The device code has expired".to_string()), - )); - } + .ok_or_else(|| { + OAuthErrorResponse::new( + OAuthErrorCode::InvalidGrant, + Some("Unknown device code or client id"), + ) + }) + .and_then(exchangeable)?; // Retrieve the real upstream device_code from the login attempt and proxy // the token exchange to the upstream provider. @@ -357,7 +356,7 @@ where let upstream_request = UpstreamDeviceTokenRequest { client_id: device_info.remote.client_id.clone(), device_code: upstream_device_code, - grant_type: body.grant_type.clone(), + grant_type: grant_type.to_string(), client_secret: device_info .remote .client_secret @@ -400,17 +399,34 @@ where match parsed { Ok(parsed) => { - // Success! The user has completed the device authorization. - - // Claim the login attempt (New -> Complete) - let attempt = ctx - .login - .claim_device_login_attempt(attempt) - .await - .map_err(|err| { - tracing::warn!(?err, "Failed to claim device login attempt"); - internal_error("Failed to claim login attempt") - })?; + // The upstream tokens are kept so that whatever is not handed back to the caller can + // be revoked + let upstream = UpstreamTokens { + access_token: Some(SecretString::from(parsed.access_token().secret().as_str())), + refresh_token: parsed + .refresh_token() + .map(|token| SecretString::from(token.secret().as_str())), + }; + + // Claim the login attempt (New -> Complete). The attempt can only be claimed after + // the upstream exchange, since every earlier poll must leave it open. Losing the claim + // means a concurrent poll completed first, so the tokens this poll obtained are + // revoked rather than left live and unaccounted for. + let claimed = ctx.login.claim_device_login_attempt(attempt.clone()).await; + let attempt = match claimed { + Ok(attempt) => Ok(attempt), + Err(err) => { + tracing::warn!( + ?err, + "Device login attempt was completed by a concurrent poll" + ); + revoke_upstream_tokens(&*provider, &attempt, &upstream).await; + Err(OAuthErrorResponse::new( + OAuthErrorCode::InvalidGrant, + Some("Device code has already been exchanged"), + )) + } + }?; // Fetch user info from the upstream provider let info = provider @@ -421,27 +437,20 @@ where tracing::debug!("Verified and validated OAuth user via device flow"); - let response = complete_exchange( - ctx, - info, - &*provider, - &attempt, - false, - UpstreamTokens::default(), - ) - .await?; + let response = + complete_exchange(ctx, info, &*provider, &attempt, false, upstream).await?; let exchange_response = response.0; - tracing::trace!( - ?exchange_response, - "Received device authorization response from upstream provider" - ); + tracing::debug!("Completed device authorization exchange"); - Ok(Response::builder() + let mut token_response = Response::builder() .status(StatusCode::OK) .header(header::CONTENT_TYPE, "application/json") - .body(serde_json::to_string(&exchange_response).unwrap().into())?) + .body(serde_json::to_string(&exchange_response).unwrap().into())?; + mark_uncacheable(token_response.headers_mut()); + + Ok(token_response) } Err(_) => { // Could not parse as a token — might be a GitHub-style 200 error @@ -457,26 +466,40 @@ where } } -/// Validate the grant_type for device code exchange per RFC 8628 §3.4. -fn validate_device_grant_type(grant_type: &str) -> bool { - grant_type == "urn:ietf:params:oauth:grant-type:device_code" +/// The grant type of a device code exchange, which must be the device code grant (RFC 8628 §3.4) +fn device_grant_type(grant_type: &str) -> Result<&'static str, OAuthErrorResponse> { + if grant_type == DEVICE_CODE_GRANT_TYPE { + Ok(DEVICE_CODE_GRANT_TYPE) + } else { + Err(OAuthErrorResponse::new( + OAuthErrorCode::UnsupportedGrantType, + Some("grant_type must be urn:ietf:params:oauth:grant-type:device_code"), + )) + } } -/// Build a JSON error response body. -fn error_response(status: StatusCode, error: &str, description: Option) -> Response { - Response::builder() - .status(status) - .header(header::CONTENT_TYPE, "application/json") - .body( - serde_json::to_vec(&ProxyTokenError { - error: error.to_string(), - error_description: description, - error_uri: None, - }) - .unwrap() - .into(), - ) - .unwrap() +/// The attempt, provided its device code can still be exchanged. That is while the attempt is +/// open and has not expired. +/// +/// An attempt without an expiration is treated as expired. +fn exchangeable(attempt: LoginAttempt) -> Result { + if attempt.attempt_state != LoginAttemptState::New { + Err(OAuthErrorResponse::new( + OAuthErrorCode::InvalidGrant, + Some("Device code has already been exchanged"), + )) + } else if attempt + .expires_at + .is_none_or(|expires_at| expires_at <= Utc::now()) + { + // TODO: Change expires_at to be non-optional. A login attempt should always have an expiration. + Err(OAuthErrorResponse::new( + OAuthErrorCode::ExpiredToken, + Some("The device code has expired"), + )) + } else { + Ok(attempt) + } } /// Headers that are safe to forward from an upstream OAuth provider response. @@ -526,14 +549,10 @@ fn handle_token_parse_failure( tracing::warn!("Remote OAuth provider returned a response that we do not understand"); Response::new( - serde_json::to_vec(&ProxyTokenError { - error: "access_denied".to_string(), - error_description: Some(format!( - "{} returned a malformed response", - provider_name - )), - error_uri: None, - }) + serde_json::to_vec(&OAuthErrorResponse::new( + OAuthErrorCode::AccessDenied, + Some(format!("{} returned a malformed response", provider_name).as_str()), + )) .unwrap() .into(), ) @@ -557,7 +576,31 @@ mod tests { }; use hyper::body::Bytes; - use super::{handle_token_parse_failure, proxy_upstream_response, validate_device_grant_type}; + use newtype_uuid::TypedUuid; + + use super::{ + configured_device_client, device_grant_type, handle_token_parse_failure, + proxy_upstream_response, + }; + use crate::endpoints::login::oauth::OAuthProviderDeviceInfo; + + /// Only the client the provider's device flow is configured for may run it + #[test] + fn only_the_configured_device_client_may_run_the_device_flow() { + let device_client = TypedUuid::new_v4(); + let device_info = OAuthProviderDeviceInfo::for_test(device_client); + + assert_eq!( + Ok(device_client), + configured_device_client(&device_info, device_client) + ); + + let refused = configured_device_client(&device_info, TypedUuid::new_v4()).unwrap_err(); + assert_eq!( + serde_json::to_value(&refused).unwrap()["error"], + serde_json::json!("invalid_client") + ); + } #[test] fn test_upstream_set_cookie_is_stripped_from_error_response() { @@ -681,29 +724,23 @@ mod tests { #[test] fn test_valid_device_grant_type_is_accepted() { - assert!(validate_device_grant_type( - "urn:ietf:params:oauth:grant-type:device_code" - )); + assert!(device_grant_type("urn:ietf:params:oauth:grant-type:device_code").is_ok()); } #[test] fn test_invalid_device_grant_type_is_rejected() { - assert!(!validate_device_grant_type("authorization_code")); + assert!(device_grant_type("authorization_code").is_err()); } #[test] fn test_empty_device_grant_type_is_rejected() { - assert!(!validate_device_grant_type("")); + assert!(device_grant_type("").is_err()); } #[test] fn test_device_grant_type_rejects_similar_values() { - assert!(!validate_device_grant_type("device_code")); - assert!(!validate_device_grant_type( - "urn:ietf:params:oauth:grant-type:device_Code" - )); - assert!(!validate_device_grant_type( - "urn:ietf:params:oauth:grant-type:authorization_code" - )); + assert!(device_grant_type("device_code").is_err()); + assert!(device_grant_type("urn:ietf:params:oauth:grant-type:device_Code").is_err()); + assert!(device_grant_type("urn:ietf:params:oauth:grant-type:authorization_code").is_err()); } } diff --git a/v-api/src/endpoints/login/oauth/flow/error.rs b/v-api/src/endpoints/login/oauth/flow/error.rs new file mode 100644 index 00000000..3a0d1d84 --- /dev/null +++ b/v-api/src/endpoints/login/oauth/flow/error.rs @@ -0,0 +1,202 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +use dropshot::{ErrorStatusCode, HttpError, HttpResponseError}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use std::fmt::{Display, Formatter}; + +use crate::{endpoints::login::LoginError, error::ApiError}; + +/// An error response as described by RFC 6749 §5.2 +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +pub struct OAuthErrorResponse { + pub error: OAuthErrorCode, + #[serde(skip_serializing_if = "Option::is_none")] + pub error_description: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub error_uri: Option, + #[serde(skip)] + #[schemars(skip)] + status: ErrorStatusCode, +} + +/// The error codes of RFC 6749 §4.1.2.1 and §5.2, and those added for the device flow by RFC 8628 +/// §3.5 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum OAuthErrorCode { + AccessDenied, + ExpiredToken, + InvalidClient, + InvalidGrant, + InvalidRequest, + InvalidScope, + ServerError, + TemporarilyUnavailable, + UnauthorizedClient, + UnsupportedGrantType, + UnsupportedResponseType, +} + +impl OAuthErrorCode { + /// The status an error with this code is answered with unless another is chosen. RFC 6749 + /// §5.2 answers client errors with 400. + fn default_status(&self) -> ErrorStatusCode { + match self { + Self::ServerError => ErrorStatusCode::INTERNAL_SERVER_ERROR, + Self::TemporarilyUnavailable => ErrorStatusCode::SERVICE_UNAVAILABLE, + _ => ErrorStatusCode::BAD_REQUEST, + } + } +} + +impl OAuthErrorResponse { + pub fn new(error: OAuthErrorCode, error_description: Option<&str>) -> Self { + Self { + error, + error_description: error_description.map(|description| description.to_string()), + error_uri: None, + status: error.default_status(), + } + } + + /// Answers the error with a different status. RFC 6749 §5.2 allows `invalid_client` to be + /// answered with 401. + pub fn with_status(mut self, status: ErrorStatusCode) -> Self { + self.status = status; + self + } +} + +impl Display for OAuthErrorResponse { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let code = serde_json::to_value(self.error) + .ok() + .and_then(|code| code.as_str().map(|code| code.to_string())) + .unwrap_or_default(); + + match &self.error_description { + Some(description) => write!(f, "{code}: {description}"), + None => write!(f, "{code}"), + } + } +} + +impl HttpResponseError for OAuthErrorResponse { + fn status_code(&self) -> ErrorStatusCode { + self.status + } +} + +impl From for OAuthErrorResponse { + fn from(error: HttpError) -> Self { + if error.status_code.is_server_error() { + tracing::error!(?error, "OAuth flow failed with a server error"); + Self::new(OAuthErrorCode::ServerError, None).with_status(error.status_code) + } else { + Self::new( + OAuthErrorCode::InvalidRequest, + Some(error.external_message.as_str()), + ) + .with_status(error.status_code) + } + } +} + +impl From for OAuthErrorResponse { + fn from(error: ApiError) -> Self { + HttpError::from(error).into() + } +} + +impl From for OAuthErrorResponse { + fn from(error: http::Error) -> Self { + HttpError::from(error).into() + } +} + +impl From for OAuthErrorResponse { + fn from(error: LoginError) -> Self { + HttpError::from(error).into() + } +} + +#[cfg(test)] +mod tests { + use dropshot::{ErrorStatusCode, HttpError, HttpResponseError}; + use serde_json::json; + + use super::{OAuthErrorCode, OAuthErrorResponse}; + + /// The response body is the bare RFC 6749 §5.2 object, without the status + #[test] + fn serializes_as_an_rfc_6749_error_response() { + let error = + OAuthErrorResponse::new(OAuthErrorCode::InvalidGrant, Some("Grant has expired")); + assert_eq!( + json!({ "error": "invalid_grant", "error_description": "Grant has expired" }), + serde_json::to_value(&error).unwrap() + ); + + let bare = OAuthErrorResponse::new(OAuthErrorCode::ExpiredToken, None); + assert_eq!( + json!({ "error": "expired_token" }), + serde_json::to_value(&bare).unwrap() + ); + } + + #[test] + fn chooses_a_status_for_each_code() { + let status = |code| OAuthErrorResponse::new(code, None).status_code(); + + assert_eq!( + ErrorStatusCode::BAD_REQUEST, + status(OAuthErrorCode::InvalidClient) + ); + assert_eq!( + ErrorStatusCode::INTERNAL_SERVER_ERROR, + status(OAuthErrorCode::ServerError) + ); + assert_eq!( + ErrorStatusCode::SERVICE_UNAVAILABLE, + status(OAuthErrorCode::TemporarilyUnavailable) + ); + assert_eq!( + ErrorStatusCode::UNAUTHORIZED, + OAuthErrorResponse::new(OAuthErrorCode::InvalidClient, None) + .with_status(ErrorStatusCode::UNAUTHORIZED) + .status_code() + ); + } + + /// Server errors never carry their message to the client, while client errors keep the message + /// that was meant for it + #[test] + fn converts_http_errors() { + let server: OAuthErrorResponse = + HttpError::for_internal_error("database exploded".to_string()).into(); + assert_eq!(OAuthErrorCode::ServerError, server.error); + assert_eq!(None, server.error_description); + assert_eq!(ErrorStatusCode::INTERNAL_SERVER_ERROR, server.status_code()); + + let client: OAuthErrorResponse = + HttpError::for_bad_request(None, "Missing client credentials".to_string()).into(); + assert_eq!(OAuthErrorCode::InvalidRequest, client.error); + assert_eq!( + Some("Missing client credentials".to_string()), + client.error_description + ); + assert_eq!(ErrorStatusCode::BAD_REQUEST, client.status_code()); + } + + #[test] + fn displays_the_code_and_description() { + assert_eq!( + "invalid_scope: Invalid scope: nope", + OAuthErrorResponse::new(OAuthErrorCode::InvalidScope, Some("Invalid scope: nope")) + .to_string() + ); + } +} diff --git a/v-api/src/endpoints/login/oauth/flow/mod.rs b/v-api/src/endpoints/login/oauth/flow/mod.rs index ece42776..e3ac0e78 100644 --- a/v-api/src/endpoints/login/oauth/flow/mod.rs +++ b/v-api/src/endpoints/login/oauth/flow/mod.rs @@ -2,8 +2,16 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use dropshot::{HttpError, HttpResponseOk}; -use oauth2::StandardRevocableToken; +use dropshot::{HttpCodedResponse, HttpError, HttpResponseHeaders, HttpResponseOk}; +use http::{ + HeaderMap, HeaderValue, + header::{CACHE_CONTROL, PRAGMA}, +}; +use newtype_uuid::GenericUuid; +use oauth2::{ + ClientId, ClientSecret, EndpointNotSet, EndpointSet, RevocationUrl, StandardRevocableToken, + basic::BasicClient, +}; use secrecy::{ExposeSecret, SecretString}; use v_model::{LoginAttempt, permissions::PermissionStorage}; @@ -13,17 +21,56 @@ use crate::{ endpoints::login::UserInfo, permissions::{VAppPermission, VPermission}, }; +use error::{OAuthErrorCode, OAuthErrorResponse}; +pub mod client_credentials; pub mod code; pub mod device_token; +pub mod error; pub use code::OAuthAuthzCodeExchangeResponse; +/// The grant type recorded on login attempts that run through the device flow (RFC 8628 §3.4) +pub(crate) const DEVICE_CODE_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:device_code"; + +/// The scope a client requested, once it has been checked to parse. An absent or empty scope +/// means no permissions, and the special scope "full" asks for every permission the principal +/// holds. +pub(crate) fn requested_scope(scope: Option<&str>) -> Result +where + T: VAppPermission, +{ + let scope = scope.unwrap_or_default(); + match T::from_scope_arg(scope) { + Ok(_) => Ok(scope.to_string()), + Err(err) => { + tracing::warn!(?err, ?scope, "Client requested an invalid scope"); + Err(OAuthErrorResponse::new( + OAuthErrorCode::InvalidScope, + Some(format!("Invalid scope: {scope}").as_str()), + )) + } + } +} + +/// Marks a response that carries an access token as one that must never be cached. Required by +/// RFC 6749 §5.1 +pub(crate) fn mark_uncacheable(headers: &mut HeaderMap) { + headers.insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); + headers.insert(PRAGMA, HeaderValue::from_static("no-cache")); +} + +/// Wraps a token response body in the headers RFC 6749 §5.1 requires of it +pub(crate) fn token_response(body: T) -> HttpResponseHeaders +where + T: HttpCodedResponse, +{ + let mut response = HttpResponseHeaders::new_unnamed(body); + mark_uncacheable(response.headers_mut()); + response +} + /// Tokens issued by the upstream identity provider during a code exchange. -/// -/// These are held separately from [`UserInfo`] so that the caller can decide, -/// after the permission check has run, whether to hand them back to the client -/// or revoke them. #[derive(Default)] pub(crate) struct UpstreamTokens { pub access_token: Option, @@ -60,7 +107,7 @@ where // a token at all. Refresh tokens are long lived, so it is important that we do not // simply drop one that we requested but are not handing back. if !provide_idp_token { - revoke_upstream_tokens(provider, &upstream).await; + revoke_upstream_tokens(provider, attempt, &upstream).await; } tracing::info!(api_user_id = ?api_user_info.user.id, "Retrieved api user to generate access token for"); @@ -77,6 +124,7 @@ where &ctx.builtin_registration_user(), &api_user_info.user.id, &api_user_provider.id, + attempt.client_id.into_untyped_uuid(), scope, ) .await?; @@ -142,16 +190,66 @@ where } } +/// An upstream client that can only revoke tokens +type RevocationClient = + BasicClient; + +/// Builds the client that revocations for a login attempt are sent as. +fn revocation_client( + provider: &dyn OAuthProvider, + attempt: &LoginAttempt, +) -> Option { + let (client_id, client_secret, endpoint) = if attempt.grant_type == DEVICE_CODE_GRANT_TYPE { + let remote = &provider.device_code_flow_info()?.remote; + ( + &remote.client_id, + &remote.client_secret, + remote.revocation_endpoint.as_ref()?, + ) + } else { + let remote = &provider.authz_code_flow_info()?.remote; + ( + &remote.client_id, + &remote.client_secret, + remote.revocation_endpoint.as_ref()?, + ) + }; + + let revocation_url = RevocationUrl::new(endpoint.clone()) + .inspect_err(|err| tracing::warn!(?err, "Provider revocation endpoint is not a valid URL")) + .ok()?; + + Some( + BasicClient::new(ClientId::new(client_id.clone())) + .set_client_secret(ClientSecret::new( + client_secret.0.expose_secret().to_string(), + )) + .set_revocation_url(revocation_url), + ) +} + /// Revoke every upstream IdP token that will not be handed back to the caller. /// -/// The refresh token is revoked first because, per RFC 7009 §2.1, revoking a -/// refresh token also invalidates the access tokens issued under the same -/// grant. The access token is revoked afterwards for providers that do not -/// cascade. -async fn revoke_upstream_tokens(provider: &dyn OAuthProvider, upstream: &UpstreamTokens) { +/// Per RFC 7009 §2.1, revoking a refresh token invalidates the access tokens +/// issued under the same grant. We revoke the access tokens as well in the +/// event the provider fails to cascade. +pub(crate) async fn revoke_upstream_tokens( + provider: &dyn OAuthProvider, + attempt: &LoginAttempt, + upstream: &UpstreamTokens, +) { + let client = match revocation_client(provider, attempt) { + Some(client) => client, + None => { + tracing::debug!("Provider does not support token revocation"); + return; + } + }; + if let Some(refresh_token) = &upstream.refresh_token { revoke_upstream_token( provider, + &client, oauth2::RefreshToken::new(refresh_token.expose_secret().to_string()).into(), ) .await; @@ -160,47 +258,61 @@ async fn revoke_upstream_tokens(provider: &dyn OAuthProvider, upstream: &Upstrea if let Some(access_token) = &upstream.access_token { revoke_upstream_token( provider, + &client, oauth2::AccessToken::new(access_token.expose_secret().to_string()).into(), ) .await; } } -/// Revoke a single upstream IdP token if the provider supports revocation. -/// Failures are logged but do not propagate — callers should not fail the -/// overall exchange just because revocation was unsuccessful. -async fn revoke_upstream_token(provider: &dyn OAuthProvider, token: StandardRevocableToken) { - let provider_info = match provider.authz_code_flow_info() { - Some(info) => info, - None => return, - }; - - if provider_info.remote.revocation_endpoint.is_some() { - let client = match provider.as_web_client() { - Ok(c) => c, - Err(err) => { - tracing::warn!( - ?err, - "Failed to build web client for upstream token revocation" - ); - return; - } - }; - let oauth_client: oauth2_reqwest::ReqwestClient = provider.client().clone().into(); - match client.revoke_token(token) { - Ok(req) => { - if let Err(err) = req.request_async(&oauth_client).await { - tracing::warn!(?err, "Failed to revoke upstream IdP token"); - } - } - Err(err) => { - tracing::warn!( - ?err, - "Failed to build revocation request for upstream token" - ); +/// Revoke a single upstream IdP token. Failures are logged but do not propagate, since the +/// overall exchange should not fail just because revocation was unsuccessful. +async fn revoke_upstream_token( + provider: &dyn OAuthProvider, + client: &RevocationClient, + token: StandardRevocableToken, +) { + let oauth_client: oauth2_reqwest::ReqwestClient = provider.client().clone().into(); + match client.revoke_token(token) { + Ok(req) => { + if let Err(err) = req.request_async(&oauth_client).await { + tracing::warn!(?err, "Failed to revoke upstream IdP token"); } } - } else { - tracing::debug!("Provider does not support token revocation") + Err(err) => { + tracing::warn!( + ?err, + "Failed to build revocation request for upstream token" + ); + } + } +} + +#[cfg(test)] +mod tests { + use dropshot::{HttpResponse, HttpResponseOk}; + use http::header::{CACHE_CONTROL, PRAGMA}; + + use super::token_response; + + /// Every token response forbids caching, as RFC 6749 §5.1 requires + #[test] + fn token_responses_are_never_cached() { + let response = token_response(HttpResponseOk(())).to_result().unwrap(); + + assert_eq!( + Some("no-store"), + response + .headers() + .get(CACHE_CONTROL) + .and_then(|value| value.to_str().ok()) + ); + assert_eq!( + Some("no-cache"), + response + .headers() + .get(PRAGMA) + .and_then(|value| value.to_str().ok()) + ); } } diff --git a/v-api/src/endpoints/login/oauth/mod.rs b/v-api/src/endpoints/login/oauth/mod.rs index b7a7b728..f2507aa8 100644 --- a/v-api/src/endpoints/login/oauth/mod.rs +++ b/v-api/src/endpoints/login/oauth/mod.rs @@ -75,7 +75,7 @@ pub trait OAuthProvider: ExtractUserInfo + Debug + Send + Sync { fn expires_in(&self) -> Option; fn default_scopes(&self) -> &[String]; - /// Whether the remote OAuth provider supports PKCE (RFC 7636). Providers must + /// Whether the remote OAuth provider supports PKCE (RFC 7636 §4). Providers must /// explicitly declare this. This controls whether v-api sends a PKCE challenge /// to the remote provider during the authorization code exchange. Note: clients /// calling v-api are always required to use PKCE regardless of this setting. @@ -221,6 +221,25 @@ pub struct OAuthProviderDeviceInfo { remote: OAuthProviderDeviceRemoteInfo, } +#[cfg(test)] +impl OAuthProviderDeviceInfo { + /// A device flow configuration for the given client, with placeholder upstream details + pub(crate) fn for_test(client_id: TypedUuid) -> Self { + Self { + client_id, + auth_url_endpoint: "https://test_public_url/login/oauth/test/device".to_string(), + token_endpoint: "https://test_public_url/login/oauth/test/device/exchange".to_string(), + remote: OAuthProviderDeviceRemoteInfo { + client_id: "remote-client".to_string(), + client_secret: OpenApiSecretString(SecretString::from("remote-secret")), + device_code_endpoint: "https://provider.test/device".to_string(), + token_endpoint: "https://provider.test/token".to_string(), + revocation_endpoint: None, + }, + } + } +} + #[derive(Clone, Debug, Serialize, JsonSchema)] pub struct OAuthProviderDeviceRemoteInfo { client_id: String, diff --git a/v-api/src/endpoints/mappers.rs b/v-api/src/endpoints/mappers.rs index ae92b09c..cf31e20d 100644 --- a/v-api/src/endpoints/mappers.rs +++ b/v-api/src/endpoints/mappers.rs @@ -13,10 +13,11 @@ use tracing::instrument; use v_model::{ Mapper, MapperId, NewMapper, permissions::{AsScope, Permission, PermissionStorage}, + storage::AccessGroupFilter, }; use crate::{ - context::{ApiContext, VContextWithCaller}, + context::{ApiContext, VContextWithCaller, mapping::AddMapperError}, permissions::{VAppPermission, VPermission}, response::{bad_request, client_error}, }; @@ -63,25 +64,30 @@ where T::AppPermissions: VAppPermission, { let (ctx, caller) = rqctx.as_ctx().await?; - if ctx.mapping.validate(&body.rule) { - let res = ctx - .mapping - .add_mapper( - &caller, - &NewMapper { - id: TypedUuid::new_v4(), - name: body.name, - rule: body.rule, - activations: body.max_activations.map(|_| 0), - max_activations: body.max_activations, - }, - ) - .await; + let visible_groups = ctx + .group + .list_groups(&caller, AccessGroupFilter::default()) + .await?; + let mapper = ctx + .mapping + .add_mapper( + &caller, + &visible_groups, + &NewMapper { + id: TypedUuid::new_v4(), + name: body.name, + rule: body.rule, + activations: body.max_activations.map(|_| 0), + max_activations: body.max_activations, + }, + ) + .await + .map_err(|err| match err { + AddMapperError::InvalidRule => bad_request("Invalid rule payload"), + AddMapperError::Resource(err) => err.into(), + })?; - Ok(HttpResponseCreated(res?)) - } else { - Err(bad_request("Invalid rule payload")) - } + Ok(HttpResponseCreated(mapper)) } #[derive(Debug, Deserialize, Serialize, JsonSchema)] diff --git a/v-api/src/endpoints/well_known/mod.rs b/v-api/src/endpoints/well_known/mod.rs index 62310c8b..28e0349c 100644 --- a/v-api/src/endpoints/well_known/mod.rs +++ b/v-api/src/endpoints/well_known/mod.rs @@ -19,6 +19,10 @@ pub struct OpenIdConfiguration { subject_types_supported: Vec, id_token_signing_alg_values_supported: Vec, claims_supported: Vec, + token_endpoint: String, + grant_types_supported: Vec, + token_endpoint_auth_methods_supported: Vec, + token_endpoint_auth_signing_alg_values_supported: Vec, } #[instrument(skip(rqctx), err(Debug))] @@ -41,6 +45,17 @@ where "exp".to_string(), "iat".to_string(), ], + token_endpoint: format!("{}/oauth/token", rqctx.v_ctx().public_url()), + grant_types_supported: vec![ + "authorization_code".to_string(), + "client_credentials".to_string(), + "urn:ietf:params:oauth:grant-type:device_code".to_string(), + ], + token_endpoint_auth_methods_supported: vec!["private_key_jwt".to_string()], + token_endpoint_auth_signing_alg_values_supported: vec![ + "Ed25519".to_string(), + "EdDSA".to_string(), + ], })) } diff --git a/v-api/src/error.rs b/v-api/src/error.rs index d24af909..ffac4e10 100644 --- a/v-api/src/error.rs +++ b/v-api/src/error.rs @@ -9,7 +9,7 @@ use v_model::storage::StoreError; use crate::{ authn::{SigningKeyError, jwt::JwtSignerError}, endpoints::login::{LoginError, oauth::OAuthProviderError}, - response::conflict, + response::{ResourceError, conflict}, util::response::{forbidden, internal_error, not_found}, }; @@ -41,6 +41,8 @@ pub enum ApiError { OAuth(#[from] OAuthProviderError), #[error("Internal storage failed {0}")] Storage(#[from] StoreError), + #[error("Internal error")] + Internal(#[source] Box), } impl From for HttpError { @@ -54,6 +56,21 @@ impl From for HttpError { ApiError::NotFound => not_found(""), ApiError::OAuth(_) => internal_error("OAuth provider failed"), ApiError::Storage(_) => internal_error("Internal storage failed"), + ApiError::Internal(_) => internal_error("Internal error"), + } + } +} + +impl From> for ApiError +where + T: std::error::Error + Send + Sync + 'static, +{ + fn from(value: ResourceError) -> ApiError { + match value { + ResourceError::Conflict => ApiError::Conflict, + ResourceError::DoesNotExist => ApiError::NotFound, + ResourceError::Restricted => ApiError::Forbidden, + ResourceError::InternalError(err) => ApiError::Internal(Box::new(err)), } } } diff --git a/v-api/src/mapper/default.rs b/v-api/src/mapper/default.rs index bfc5a957..1a68aec0 100644 --- a/v-api/src/mapper/default.rs +++ b/v-api/src/mapper/default.rs @@ -3,72 +3,57 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use async_trait::async_trait; -use newtype_uuid::TypedUuid; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use std::collections::BTreeSet; -use tracing::instrument; -use v_model::{ - AccessGroupId, - permissions::{Caller, Permissions}, - storage::{AccessGroupFilter, StoreError}, -}; +use serde_json::Value; -use crate::{ - context::group::GroupContext, endpoints::login::UserInfo, permissions::VAppPermission, - util::response::ResourceResult, -}; +use crate::endpoints::login::UserInfo; -use super::MapperRule; +use super::{MapperRule, MappingGrants}; -pub struct DefaultMapper { - caller: Caller, - group: GroupContext, - data: DefaultMapperData, +/// Adds all users to a set of groups. +pub struct DefaultMapper { + grants: MappingGrants, } #[derive(Debug, Deserialize, Serialize, JsonSchema)] -pub struct DefaultMapperData { - permissions: Option>, +#[serde(deny_unknown_fields)] +pub struct DefaultMapperData { + groups: Vec, +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +pub struct DefaultMapperDataV1 { + permissions: Option, #[serde(default)] groups: Vec, } -impl DefaultMapper { - pub fn new(caller: Caller, group: GroupContext, data: DefaultMapperData) -> Self { +impl DefaultMapper { + pub fn new(data: DefaultMapperData) -> Self { Self { - caller, - group, - data, + grants: MappingGrants { + groups: data.groups, + }, + } + } + + pub fn from_v1(data: DefaultMapperDataV1) -> Self { + Self { + grants: MappingGrants { + groups: data.groups, + }, } } } #[async_trait] -impl MapperRule for DefaultMapper -where - T: VAppPermission, -{ - #[instrument(skip(self, _user), field(data = ?self.data))] - async fn permissions_for(&self, _user: &UserInfo) -> Result, StoreError> { - tracing::trace!("Running default mapper"); - Ok(self.data.permissions.clone().unwrap_or_default()) +impl MapperRule for DefaultMapper { + fn grants(&self) -> &MappingGrants { + &self.grants } - #[instrument(skip(self, _user), field(data = ?self.data))] - async fn groups_for( - &self, - _user: &UserInfo, - ) -> ResourceResult>, StoreError> { - tracing::trace!("Running default mapper"); - let known_groups = self - .group - .list_groups(&self.caller, AccessGroupFilter::default()) - .await?; - - Ok(super::resolve_mapped_groups( - &self.data.groups, - &known_groups, - )) + async fn matches(&self, _user: &UserInfo) -> bool { + true } } diff --git a/v-api/src/mapper/email_address.rs b/v-api/src/mapper/email_address.rs index 6fc2cde4..4ba73cea 100644 --- a/v-api/src/mapper/email_address.rs +++ b/v-api/src/mapper/email_address.rs @@ -3,92 +3,64 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use async_trait::async_trait; -use newtype_uuid::TypedUuid; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use std::collections::BTreeSet; -use tracing::instrument; -use v_model::{ - AccessGroupId, - permissions::{Caller, Permissions}, - storage::{AccessGroupFilter, StoreError}, -}; +use serde_json::Value; -use crate::{ - context::group::GroupContext, endpoints::login::UserInfo, permissions::VAppPermission, - util::response::ResourceResult, -}; +use crate::endpoints::login::UserInfo; -use super::MapperRule; +use super::{MapperRule, MappingGrants}; -pub struct EmailAddressMapper { - caller: Caller, - group: GroupContext, - data: EmailAddressMapperData, +/// Adds a user with a specific verified email address to a set of groups. +pub struct EmailAddressMapper { + email: String, + grants: MappingGrants, } #[derive(Debug, Deserialize, Serialize, JsonSchema)] -pub struct EmailAddressMapperData { +#[serde(deny_unknown_fields)] +pub struct EmailAddressMapperData { email: String, - permissions: Option>, + groups: Vec, +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +pub struct EmailAddressMapperDataV1 { + email: String, + permissions: Option, #[serde(default)] groups: Vec, } -impl EmailAddressMapper { - pub fn new(caller: Caller, group: GroupContext, data: EmailAddressMapperData) -> Self { +impl EmailAddressMapper { + pub fn new(data: EmailAddressMapperData) -> Self { Self { - caller, - group, - data, + email: data.email, + grants: MappingGrants { + groups: data.groups, + }, } } -} - -#[async_trait] -impl MapperRule for EmailAddressMapper -where - T: VAppPermission, -{ - #[instrument(skip(self, user), field(data = ?self.data))] - async fn permissions_for(&self, user: &UserInfo) -> Result, StoreError> { - tracing::trace!("Running email address mapper"); - if user - .verified_emails - .iter() - .any(|email| email == &self.data.email) - { - Ok(self.data.permissions.clone().unwrap_or_default()) - } else { - Ok(Permissions::new()) + pub fn from_v1(data: EmailAddressMapperDataV1) -> Self { + Self { + email: data.email, + grants: MappingGrants { + groups: data.groups, + }, } } +} - #[instrument(skip(self, user), field(data = ?self.data))] - async fn groups_for( - &self, - user: &UserInfo, - ) -> ResourceResult>, StoreError> { - tracing::trace!("Running email address mapper"); +#[async_trait] +impl MapperRule for EmailAddressMapper { + fn grants(&self) -> &MappingGrants { + &self.grants + } - let found_email = user - .verified_emails + async fn matches(&self, user: &UserInfo) -> bool { + user.verified_emails .iter() - .any(|email| email == &self.data.email); - - if found_email { - let known_groups = self - .group - .list_groups(&self.caller, AccessGroupFilter::default()) - .await?; - - Ok(super::resolve_mapped_groups( - &self.data.groups, - &known_groups, - )) - } else { - Ok(BTreeSet::new()) - } + .any(|email| email == &self.email) } } diff --git a/v-api/src/mapper/email_domain.rs b/v-api/src/mapper/email_domain.rs index 224e1a24..c33e7933 100644 --- a/v-api/src/mapper/email_domain.rs +++ b/v-api/src/mapper/email_domain.rs @@ -3,151 +3,91 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use async_trait::async_trait; -use newtype_uuid::TypedUuid; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use std::collections::BTreeSet; -use tracing::instrument; -use v_model::{ - AccessGroupId, - permissions::{Caller, Permissions}, - storage::{AccessGroupFilter, StoreError}, -}; - -use crate::{ - context::group::GroupContext, endpoints::login::UserInfo, permissions::VAppPermission, - util::response::ResourceResult, -}; - -use super::MapperRule; - -pub struct EmailDomainMapper { - caller: Caller, - group: GroupContext, - data: EmailDomainMapperData, +use serde_json::Value; + +use crate::endpoints::login::UserInfo; + +use super::{MapperRule, MappingGrants}; + +/// Adds a user with a verified email address in a specific domain to a set of groups. +pub struct EmailDomainMapper { + domain: String, + grants: MappingGrants, } #[derive(Debug, Deserialize, Serialize, JsonSchema)] -pub struct EmailDomainMapperData { +#[serde(deny_unknown_fields)] +pub struct EmailDomainMapperData { domain: String, - permissions: Option>, + groups: Vec, +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +pub struct EmailDomainMapperDataV1 { + domain: String, + permissions: Option, #[serde(default)] groups: Vec, } -impl EmailDomainMapper { - pub fn new(caller: Caller, group: GroupContext, data: EmailDomainMapperData) -> Self { +impl EmailDomainMapper { + pub fn new(data: EmailDomainMapperData) -> Self { Self { - caller, - group, - data, + domain: data.domain, + grants: MappingGrants { + groups: data.groups, + }, + } + } + + pub fn from_v1(data: EmailDomainMapperDataV1) -> Self { + Self { + domain: data.domain, + grants: MappingGrants { + groups: data.groups, + }, } } } #[async_trait] -impl MapperRule for EmailDomainMapper -where - T: VAppPermission, -{ - #[instrument(skip(self, _user), field(data = ?self.data))] - async fn permissions_for(&self, _user: &UserInfo) -> Result, StoreError> { - Ok(Permissions::new()) +impl MapperRule for EmailDomainMapper { + fn grants(&self) -> &MappingGrants { + &self.grants } - #[instrument(skip(self, user), field(data = ?self.data))] - async fn groups_for( - &self, - user: &UserInfo, - ) -> ResourceResult>, StoreError> { - tracing::trace!("Running email domain mapper"); - let has_email_in_domain = user.verified_emails.iter().any(|email| { + async fn matches(&self, user: &UserInfo) -> bool { + user.verified_emails.iter().any(|email| { let mut parts = email.split('@'); parts .nth(1) - .map(|domain| domain == self.data.domain) + .map(|domain| domain == self.domain) .unwrap_or(false) - }); - - if has_email_in_domain { - let known_groups = self - .group - .list_groups(&self.caller, AccessGroupFilter::default()) - .await?; - - Ok(super::resolve_mapped_groups( - &self.data.groups, - &known_groups, - )) - } else { - Ok(BTreeSet::new()) - } + }) } } #[cfg(test)] mod tests { - use std::{collections::BTreeSet, sync::Arc}; - - use chrono::Utc; - use newtype_uuid::TypedUuid; - use std::collections::HashMap; - use v_model::{ - AccessGroup, AccessGroupSource, - permissions::{Caller, Permissions}, - storage::MockAccessGroupStore, - }; + use serde_json::json; use crate::{ - context::{group::GroupContext, test_mocks::MockStorage}, endpoints::login::{ExternalUserId, UserInfo}, mapper::MapperRule, - permissions::VPermission, }; use super::{EmailDomainMapper, EmailDomainMapperData}; - /// Build a `GroupContext` whose backing store returns a single group with - /// the provided name/id, mimicking a deployment that has an "employees" - /// group reserved for members of a configured email domain. - fn group_context_with_group( - group_id: TypedUuid, - group_name: &str, - ) -> GroupContext { - let group = AccessGroup { - id: group_id, - name: group_name.to_string(), - permissions: Permissions::::new(), - source: AccessGroupSource::Dynamic, - created_at: Utc::now(), - updated_at: Utc::now(), - deleted_at: None, - }; - - let mut group_store = MockAccessGroupStore::new(); - group_store - .expect_list() - .returning(move |_, _| Ok(vec![group.clone()])); - - let mut storage = MockStorage::new(); - storage.access_group_store = Some(Arc::new(group_store)); - - GroupContext::new(Arc::new(storage)) - } - - /// Mirror the builtin registration caller, which the mapping engine uses - /// when running mappers during `register_api_user`. It holds broad group - /// permissions, so every matched group is unconditionally granted. - fn registration_caller() -> Caller { - Caller { - id: "00000000-0000-4000-8000-000000000001".parse().unwrap(), - permissions: vec![ - VPermission::GetGroupsAll, - VPermission::ManageGroupMembershipsAll, - ] - .into(), - extensions: HashMap::default(), - } + fn employees_mapper() -> EmailDomainMapper { + EmailDomainMapper::new( + serde_json::from_value::(json!({ + "domain": "example.com", + "groups": ["employees"], + })) + .unwrap(), + ) } fn user_with_email(email: &str) -> UserInfo { @@ -159,83 +99,39 @@ mod tests { } } - /// Sanity check: a genuine member of the configured domain is mapped into - /// the reserved group. This is the intended behavior. + /// As a sanity check, a genuine member of the configured domain matches and is handed the + /// reserved group. This is the intended behavior. #[tokio::test] - async fn maps_legitimate_domain_member_into_group() { - let group_id = TypedUuid::new_v4(); - let mapper = EmailDomainMapper::new( - registration_caller(), - group_context_with_group(group_id, "employees"), - EmailDomainMapperData:: { - domain: "example.com".to_string(), - permissions: None, - groups: vec!["employees".to_string()], - }, - ); + async fn matches_legitimate_domain_member() { + let mapper = employees_mapper(); - let groups = mapper - .groups_for(&user_with_email("alice@example.com")) - .await - .unwrap(); - - assert_eq!(groups, BTreeSet::from([group_id])); + assert!(mapper.matches(&user_with_email("alice@example.com")).await); + assert_eq!(vec!["employees".to_string()], mapper.grants().groups); } - /// Exploit: an attacker who owns a lookalike domain whose name merely - /// *ends with* the configured domain (`evilexample.com` vs `example.com`) - /// is granted the reserved group. The `ends_with` check on - /// `email.ends_with(&self.data.domain)` has no `@`/`.` boundary, so - /// `a@evilexample.com`.ends_with(`example.com`) is true. + /// An attacker who owns a lookalike domain whose name merely *ends with* the + /// configured domain (`evilexample.com` vs `example.com`) must not match. An `ends_with` + /// check without an `@` boundary would treat `a@evilexample.com` as a member. #[tokio::test] - async fn lookalike_domain_must_not_be_granted_reserved_group() { - let group_id = TypedUuid::new_v4(); - let mapper = EmailDomainMapper::new( - registration_caller(), - group_context_with_group(group_id, "employees"), - EmailDomainMapperData:: { - domain: "example.com".to_string(), - permissions: None, - groups: vec!["employees".to_string()], - }, - ); - - // Attacker-controlled address at a domain the attacker registered. + async fn lookalike_domain_must_not_match() { let attacker = user_with_email("a@evilexample.com"); - let groups = mapper.groups_for(&attacker).await.unwrap(); assert!( - groups.is_empty(), - "authorization bypass: an attacker owning the lookalike domain \ - 'evilexample.com' was granted the reserved groups {:?} intended \ - only for 'example.com' members", - groups, + !employees_mapper().matches(&attacker).await, + "authorization bypass: an attacker owning the lookalike domain 'evilexample.com' \ + matched a rule intended only for 'example.com' members", ); } - /// A related boundary case: a bare-suffix match without any `@` separator + /// In a related boundary case, a bare suffix match without any `@` separator /// (`notexample.com`) must also be rejected. #[tokio::test] - async fn suffix_only_domain_must_not_be_granted_reserved_group() { - let group_id = TypedUuid::new_v4(); - let mapper = EmailDomainMapper::new( - registration_caller(), - group_context_with_group(group_id, "employees"), - EmailDomainMapperData:: { - domain: "example.com".to_string(), - permissions: None, - groups: vec!["employees".to_string()], - }, - ); - + async fn suffix_only_domain_must_not_match() { let attacker = user_with_email("user@notexample.com"); - let groups = mapper.groups_for(&attacker).await.unwrap(); assert!( - groups.is_empty(), - "authorization bypass: 'notexample.com' was treated as a member of \ - 'example.com' and granted {:?}", - groups, + !employees_mapper().matches(&attacker).await, + "authorization bypass: 'notexample.com' was treated as a member of 'example.com'", ); } } diff --git a/v-api/src/mapper/github_username.rs b/v-api/src/mapper/github_username.rs index 8f9308e7..9fa0a34b 100644 --- a/v-api/src/mapper/github_username.rs +++ b/v-api/src/mapper/github_username.rs @@ -3,273 +3,138 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use async_trait::async_trait; -use newtype_uuid::TypedUuid; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use std::collections::BTreeSet; -use v_model::{ - AccessGroupId, - permissions::{Caller, Permissions}, - storage::{AccessGroupFilter, StoreError}, -}; +use serde_json::Value; -use crate::{ - context::group::GroupContext, - endpoints::login::{ExternalUserId, UserInfo}, - permissions::VAppPermission, - util::response::ResourceResult, -}; +use crate::endpoints::login::{ExternalUserId, UserInfo}; -use super::MapperRule; +use super::{MapperRule, MappingGrants}; -pub struct GitHubUsernameMapper { - caller: Caller, - group: GroupContext, - data: GitHubUsernameMapperData, +/// Adds a user with a specific GitHub username to a set of groups. +pub struct GitHubUsernameMapper { + github_username: String, + grants: MappingGrants, +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct GitHubUsernameMapperData { + github_username: String, + groups: Vec, } #[derive(Debug, Deserialize, Serialize, JsonSchema)] -pub struct GitHubUsernameMapperData { +pub struct GitHubUsernameMapperDataV1 { github_username: String, - permissions: Option>, + permissions: Option, #[serde(default)] groups: Vec, } -impl GitHubUsernameMapper { - pub fn new( - caller: Caller, - group: GroupContext, - data: GitHubUsernameMapperData, - ) -> Self { +impl GitHubUsernameMapper { + pub fn new(data: GitHubUsernameMapperData) -> Self { Self { - caller, - group, - data, + github_username: data.github_username, + grants: MappingGrants { + groups: data.groups, + }, + } + } + + pub fn from_v1(data: GitHubUsernameMapperDataV1) -> Self { + Self { + github_username: data.github_username, + grants: MappingGrants { + groups: data.groups, + }, } } } #[async_trait] -impl MapperRule for GitHubUsernameMapper -where - T: VAppPermission, -{ - async fn permissions_for(&self, user: &UserInfo) -> Result, StoreError> { - if matches!(user.external_id, ExternalUserId::GitHub(_)) { - if user - .display_name - .as_ref() - .map(|u| u == &self.data.github_username) - .unwrap_or(false) - { - Ok(self.data.permissions.clone().unwrap_or_default()) - } else { - Ok(Permissions::new()) - } - } else { - Ok(Permissions::new()) - } +impl MapperRule for GitHubUsernameMapper { + fn grants(&self) -> &MappingGrants { + &self.grants } - async fn groups_for( - &self, - user: &UserInfo, - ) -> ResourceResult>, StoreError> { - if matches!(user.external_id, ExternalUserId::GitHub(_)) { - if user + /// Only a GitHub login can match. Display names from other providers are freely editable by + /// their owners, so they say nothing about who holds a GitHub username. + async fn matches(&self, user: &UserInfo) -> bool { + matches!(user.external_id, ExternalUserId::GitHub(_)) + && user .display_name .as_ref() - .map(|u| u == &self.data.github_username) + .map(|name| name == &self.github_username) .unwrap_or(false) - { - let known_groups = self - .group - .list_groups(&self.caller, AccessGroupFilter::default()) - .await?; - - Ok(super::resolve_mapped_groups( - &self.data.groups, - &known_groups, - )) - } else { - Ok(BTreeSet::new()) - } - } else { - Ok(BTreeSet::new()) - } } } #[cfg(test)] mod tests { - use std::{collections::BTreeSet, collections::HashMap, sync::Arc}; - - use chrono::Utc; - use newtype_uuid::TypedUuid; - use v_model::{ - AccessGroup, AccessGroupSource, - permissions::{Caller, Permissions}, - storage::MockAccessGroupStore, - }; - use crate::{ - context::{group::GroupContext, test_mocks::MockStorage}, endpoints::login::{ExternalUserId, UserInfo}, mapper::MapperRule, - permissions::VPermission, }; use super::{GitHubUsernameMapper, GitHubUsernameMapperData}; - /// Build a `GroupContext` whose backing store returns a single group with - /// the provided name/id, mimicking a deployment that has a "contributors" - /// group reserved for a trusted GitHub contributor. - fn group_context_with_group( - group_id: TypedUuid, - group_name: &str, - ) -> GroupContext { - let group = AccessGroup { - id: group_id, - name: group_name.to_string(), - permissions: Permissions::::new(), - source: AccessGroupSource::Dynamic, - created_at: Utc::now(), - updated_at: Utc::now(), - deleted_at: None, - }; - - let mut group_store = MockAccessGroupStore::new(); - group_store - .expect_list() - .returning(move |_, _| Ok(vec![group.clone()])); - - let mut storage = MockStorage::new(); - storage.access_group_store = Some(Arc::new(group_store)); - - GroupContext::new(Arc::new(storage)) + /// A mapper configured to trust the GitHub username "trusted-dev", granting the + /// `GetMappersAll` permission and membership in the "contributors" group. + fn trusted_dev_mapper() -> GitHubUsernameMapper { + GitHubUsernameMapper::new(GitHubUsernameMapperData { + github_username: "trusted-dev".to_string(), + groups: vec!["contributors".to_string()], + }) } - /// Mirror the builtin registration caller, which the mapping engine uses - /// when running mappers during `register_api_user`. It can grant anything, - /// so every matched group is unconditionally granted. - fn registration_caller() -> Caller { - Caller { - id: "00000000-0000-4000-8000-000000000001".parse().unwrap(), - permissions: vec![ - VPermission::GetGroupsAll, - VPermission::ManageGroupMembershipsAll, - ] - .into(), - extensions: HashMap::default(), + fn user(external_id: ExternalUserId) -> UserInfo { + UserInfo { + external_id, + verified_emails: vec!["trusted-dev@example.com".to_string()], + display_name: Some("trusted-dev".to_string()), + idp_token: None, } } - /// A mapper configured to trust the GitHub username "trusted-dev", granting - /// the `GetMappersAll` permission and membership in the "contributors" - /// group. - fn trusted_dev_mapper( - group_id: TypedUuid, - ) -> GitHubUsernameMapper { - GitHubUsernameMapper::new( - registration_caller(), - group_context_with_group(group_id, "contributors"), - GitHubUsernameMapperData:: { - github_username: "trusted-dev".to_string(), - permissions: Some(vec![VPermission::GetMappersAll].into()), - groups: vec!["contributors".to_string()], - }, - ) - } - - /// Sanity check: a genuine GitHub login whose login/display name is - /// "trusted-dev" receives the mapped permissions and groups. This is the - /// intended behavior. + /// As a sanity check, a genuine GitHub login whose login or display name is "trusted-dev" + /// matches and is handed the mapped permissions and groups. This is the intended behavior. #[tokio::test] - async fn maps_genuine_github_user() { - let group_id = TypedUuid::new_v4(); - let mapper = trusted_dev_mapper(group_id); + async fn matches_genuine_github_user() { + let mapper = trusted_dev_mapper(); - let github_user = UserInfo { - external_id: ExternalUserId::GitHub("trusted-dev".to_string()), - verified_emails: vec!["trusted-dev@example.com".to_string()], - display_name: Some("trusted-dev".to_string()), - idp_token: None, - }; - - assert_eq!( - mapper.permissions_for(&github_user).await.unwrap(), - Permissions::::from(vec![VPermission::GetMappersAll]), - ); - assert_eq!( - mapper.groups_for(&github_user).await.unwrap(), - BTreeSet::from([group_id]), + assert!( + mapper + .matches(&user(ExternalUserId::GitHub("trusted-dev".to_string()))) + .await ); + assert_eq!(vec!["contributors".to_string()], mapper.grants().groups); } - /// Exploit: an attacker with a free Google account sets the account's - /// freely-editable profile display name to "trusted-dev" and logs in via - /// the Google OAuth flow. Because the mapper only compares - /// `user.display_name` and never checks that `user.external_id` is the - /// GitHub variant, the attacker impersonates the trusted GitHub - /// contributor and is granted their permissions and groups. + /// An attacker with a free Google account sets the account's freely editable + /// profile display name to "trusted-dev" and logs in via the Google OAuth flow. Comparing + /// only the display name without checking the provider would let them impersonate the + /// trusted GitHub contributor. #[tokio::test] async fn google_login_must_not_impersonate_github_user() { - let group_id = TypedUuid::new_v4(); - let mapper = trusted_dev_mapper(group_id); + let attacker = user(ExternalUserId::Google("attacker-google-id".to_string())); - // Attacker's throwaway Google account with a spoofed display name. - let attacker = UserInfo { - external_id: ExternalUserId::Google("attacker-google-id".to_string()), - verified_emails: vec!["attacker@gmail.com".to_string()], - display_name: Some("trusted-dev".to_string()), - idp_token: None, - }; - - let permissions = mapper.permissions_for(&attacker).await.unwrap(); - assert!( - permissions.is_empty(), - "authorization bypass: a Google login with a spoofed display name \ - 'trusted-dev' was granted the GitHub-mapped permissions {:?}", - permissions, - ); - - let groups = mapper.groups_for(&attacker).await.unwrap(); assert!( - groups.is_empty(), - "authorization bypass: a Google login with a spoofed display name \ - 'trusted-dev' was granted the GitHub-mapped groups {:?}", - groups, + !trusted_dev_mapper().matches(&attacker).await, + "authorization bypass: a Google login with a spoofed display name 'trusted-dev' \ + matched the GitHub username rule", ); } - /// The same bypass applies to Zendesk, whose `user.name` is self-editable. + /// The same bypass applies to Zendesk, whose `user.name` is self editable. #[tokio::test] async fn zendesk_login_must_not_impersonate_github_user() { - let group_id = TypedUuid::new_v4(); - let mapper = trusted_dev_mapper(group_id); - - let attacker = UserInfo { - external_id: ExternalUserId::Zendesk("attacker-zendesk-id".to_string()), - verified_emails: vec!["attacker@zendesk.example".to_string()], - display_name: Some("trusted-dev".to_string()), - idp_token: None, - }; - - let permissions = mapper.permissions_for(&attacker).await.unwrap(); - assert!( - permissions.is_empty(), - "authorization bypass: a Zendesk login with a spoofed display name \ - 'trusted-dev' was granted the GitHub-mapped permissions {:?}", - permissions, - ); + let attacker = user(ExternalUserId::Zendesk("attacker-zendesk-id".to_string())); - let groups = mapper.groups_for(&attacker).await.unwrap(); assert!( - groups.is_empty(), - "authorization bypass: a Zendesk login with a spoofed display name \ - 'trusted-dev' was granted the GitHub-mapped groups {:?}", - groups, + !trusted_dev_mapper().matches(&attacker).await, + "authorization bypass: a Zendesk login with a spoofed display name 'trusted-dev' \ + matched the GitHub username rule", ); } } diff --git a/v-api/src/mapper/mod.rs b/v-api/src/mapper/mod.rs index 05b5b88b..d3b27413 100644 --- a/v-api/src/mapper/mod.rs +++ b/v-api/src/mapper/mod.rs @@ -3,10 +3,10 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use async_trait::async_trait; -use default::DefaultMapperData; -use email_address::EmailAddressMapperData; -use email_domain::EmailDomainMapperData; -use github_username::GitHubUsernameMapperData; +use default::{DefaultMapperData, DefaultMapperDataV1}; +use email_address::{EmailAddressMapperData, EmailAddressMapperDataV1}; +use email_domain::{EmailDomainMapperData, EmailDomainMapperDataV1}; +use github_username::{GitHubUsernameMapperData, GitHubUsernameMapperDataV1}; use newtype_uuid::TypedUuid; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -14,16 +14,9 @@ use serde_json::Value; use std::{collections::BTreeSet, error::Error as StdError, fmt::Debug}; use tap::TapFallible; use thiserror::Error; -use v_model::{ - AccessGroup, AccessGroupId, Mapper, - permissions::{Caller, Permissions}, - storage::StoreError, -}; +use v_model::{AccessGroup, AccessGroupId}; -use crate::{ - context::group::GroupContext, endpoints::login::UserInfo, permissions::VAppPermission, - util::response::ResourceResult, -}; +use crate::endpoints::login::UserInfo; use self::{ default::DefaultMapper, email_address::EmailAddressMapper, email_domain::EmailDomainMapper, @@ -36,18 +29,11 @@ pub mod email_domain; pub mod github_username; #[async_trait] -/// Mapping rules that determine permissions and groups for users -pub trait MapperRule: Send + Sync -where - T: VAppPermission, -{ - /// Determines the permissions for a given user. - async fn permissions_for(&self, user: &UserInfo) -> Result, StoreError>; - /// Determines the access groups for a given user. - async fn groups_for( - &self, - user: &UserInfo, - ) -> ResourceResult>, StoreError>; +pub trait MapperRule: Send + Sync + 'static { + /// Everything the rule hands to a user it matches. + fn grants(&self) -> &MappingGrants; + /// Whether the rule applies to the given user. + async fn matches(&self, user: &UserInfo) -> bool; } #[derive(Debug, Error)] @@ -58,11 +44,25 @@ pub enum MappingEngineError { Other(Box), } +/// What a mapping rule assigns to a user. +#[derive(Debug, Clone, PartialEq)] +pub struct MappingGrants { + /// Names of the groups a matched user is added to. + pub groups: Vec, +} + /// Interface for generating mapping rules from mapper configurations -pub trait MappingEngine: Send + Sync + 'static { - /// Creates a new mapping rule from a Mapper configuration - fn create_mapping(&self, value: Mapper) -> Result>, MappingEngineError>; - /// Validates whether the provided data represents a known mapping rule +pub trait MappingEngine: Send + Sync + 'static { + // TODO: Would love to fix this so it isn't a Value... + /// Independent of a mapper rule being valid, and engine may only accept a mapper based on + /// arbitrary restrictions. + fn is_accepted(&self, value: &Value) -> bool; + // TODO: Would love to fix this so it isn't a Value... + /// Creates a mapping rule from a blob of rule data. This must be backwards compatible in terms + /// of reading and parsing rules. The output is expected to be a current rule. + fn create_mapping(&self, rule: &Value) -> Result, MappingEngineError>; + // TODO: Would love to fix this so it isn't a Value... + /// Validates whether the provided data represents a known mapping rule. fn validate_mapping_data(&self, value: &Value) -> bool; } @@ -94,79 +94,87 @@ pub(crate) fn resolve_mapped_groups( } /// Default implementation of the MappingEngine trait -pub struct DefaultMappingEngine { - caller: Caller, - group: GroupContext, -} +#[derive(Default)] +pub struct DefaultMappingEngine; -impl DefaultMappingEngine -where - T: VAppPermission, -{ - pub fn new(caller: Caller, group: GroupContext) -> Self { - Self { caller, group } - } +/// Current mapping rules that have dropped support for direct permission assignments, and require +/// at least one group assignment. +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(tag = "rule", rename_all = "snake_case")] +pub enum MappingRulesData { + Default(DefaultMapperData), + EmailAddress(EmailAddressMapperData), + EmailDomain(EmailDomainMapperData), + #[serde(rename = "github_username")] + GitHubUsername(GitHubUsernameMapperData), } -/// The default mapping rule configurations that are supported by the default mapping engine +/// V1 rules can carry permission assignments which are no longer supported. #[derive(Debug, Deserialize, Serialize, JsonSchema)] #[serde(tag = "rule", rename_all = "snake_case")] -pub enum MappingRulesData { - Default(DefaultMapperData), - EmailAddress(EmailAddressMapperData), - EmailDomain(EmailDomainMapperData), +pub enum MappingRulesDataV1 { + Default(DefaultMapperDataV1), + EmailAddress(EmailAddressMapperDataV1), + EmailDomain(EmailDomainMapperDataV1), #[serde(rename = "github_username")] - GitHubUsername(GitHubUsernameMapperData), + GitHubUsername(GitHubUsernameMapperDataV1), +} + +/// A rule as it may be stored. This may be either a legacy v1 rule or a current rule. +#[derive(Debug, Deserialize)] +#[serde(untagged)] +enum StoredMappingRule { + Current(MappingRulesData), + V1(MappingRulesDataV1), } -impl MappingEngine for DefaultMappingEngine -where - T: VAppPermission, -{ - fn create_mapping(&self, value: Mapper) -> Result>, MappingEngineError> { - serde_json::from_value::>(value.rule) +impl From for Box { + fn from(rule: StoredMappingRule) -> Self { + match rule { + StoredMappingRule::Current(MappingRulesData::Default(data)) => { + Box::new(DefaultMapper::new(data)) + } + StoredMappingRule::Current(MappingRulesData::EmailAddress(data)) => { + Box::new(EmailAddressMapper::new(data)) + } + StoredMappingRule::Current(MappingRulesData::EmailDomain(data)) => { + Box::new(EmailDomainMapper::new(data)) + } + StoredMappingRule::Current(MappingRulesData::GitHubUsername(data)) => { + Box::new(GitHubUsernameMapper::new(data)) + } + StoredMappingRule::V1(MappingRulesDataV1::Default(data)) => { + Box::new(DefaultMapper::from_v1(data)) + } + StoredMappingRule::V1(MappingRulesDataV1::EmailAddress(data)) => { + Box::new(EmailAddressMapper::from_v1(data)) + } + StoredMappingRule::V1(MappingRulesDataV1::EmailDomain(data)) => { + Box::new(EmailDomainMapper::from_v1(data)) + } + StoredMappingRule::V1(MappingRulesDataV1::GitHubUsername(data)) => { + Box::new(GitHubUsernameMapper::from_v1(data)) + } + } + } +} + +impl MappingEngine for DefaultMappingEngine { + fn is_accepted(&self, value: &Value) -> bool { + serde_json::from_value::(value.clone()).is_ok() + } + + fn create_mapping(&self, rule: &Value) -> Result, MappingEngineError> { + serde_json::from_value::(rule.clone()) .map_err(|err| { tracing::error!(?err, "Failed to translate stored rule to mapper"); MappingEngineError::Other(Box::new(err)) }) - .map(move |rule| match rule { - MappingRulesData::Default(data) => { - let res: Box> = Box::new(DefaultMapper::new( - self.caller.clone(), - self.group.clone(), - data, - )); - res - } - MappingRulesData::EmailAddress(data) => { - let res: Box> = Box::new(EmailAddressMapper::new( - self.caller.clone(), - self.group.clone(), - data, - )); - res - } - MappingRulesData::EmailDomain(data) => { - let res: Box> = Box::new(EmailDomainMapper::new( - self.caller.clone(), - self.group.clone(), - data, - )); - res - } - MappingRulesData::GitHubUsername(data) => { - let res: Box> = Box::new(GitHubUsernameMapper::new( - self.caller.clone(), - self.group.clone(), - data, - )); - res - } - }) + .map(Box::::from) } fn validate_mapping_data(&self, value: &Value) -> bool { - serde_json::from_value::>(value.clone()) + serde_json::from_value::(value.clone()) .tap_err(|err| { tracing::warn!(?value, ?err, "Failed to parse mapping rule"); }) @@ -178,11 +186,87 @@ where mod tests { use chrono::Utc; use newtype_uuid::TypedUuid; + use serde_json::{Value, json}; use v_model::{AccessGroup, AccessGroupSource, permissions::Permissions}; use crate::permissions::VPermission; - use super::resolve_mapped_groups; + use super::{DefaultMappingEngine, MappingEngine, resolve_mapped_groups}; + + fn create(rule: Value) -> super::MappingGrants { + DefaultMappingEngine + .create_mapping(&rule) + .unwrap_or_else(|err| panic!("{rule} was not read: {err}")) + .grants() + .clone() + } + + /// One rule of each type in the original shape, granting permissions alongside groups + fn original_rules(permissions: &Value) -> Vec { + vec![ + json!({ "rule": "default", "permissions": permissions, "groups": ["a"] }), + json!({ "rule": "email_address", "email": "a@example.com", "permissions": permissions, "groups": ["a"] }), + json!({ "rule": "email_domain", "domain": "example.com", "permissions": permissions, "groups": ["a"] }), + json!({ "rule": "github_username", "github_username": "a", "permissions": permissions, "groups": ["a"] }), + ] + } + + /// Rules stored before mappers were limited to groups keep only their groups + #[test] + fn reads_rules_in_the_original_shape() { + let permissions = serde_json::to_value(Permissions::::from(vec![ + VPermission::CreateGroup, + ])) + .unwrap(); + + for rule in original_rules(&permissions) { + let grants = create(rule.clone()); + assert_eq!(vec!["a".to_string()], grants.groups, "{rule}"); + } + } + + /// In the original shape a rule could leave out its groups entirely + #[test] + fn reads_original_rules_without_groups() { + let permissions = serde_json::to_value(Permissions::::from(vec![ + VPermission::CreateGroup, + ])) + .unwrap(); + let grants = create(json!({ "rule": "default", "permissions": permissions })); + + assert!(grants.groups.is_empty()); + + let grants = create(json!({ "rule": "email_domain", "domain": "example.com" })); + assert!(grants.groups.is_empty()); + } + + /// A rule in the current shape grants only groups + #[test] + fn current_rules_grant_no_permissions() { + let grants = create(json!({ "rule": "default", "groups": ["a"] })); + + assert_eq!(vec!["a".to_string()], grants.groups); + } + + #[test] + fn all_rules_should_validate() { + let engine = DefaultMappingEngine; + let permissions = serde_json::to_value(Permissions::::from(vec![ + VPermission::CreateGroup, + ])) + .unwrap(); + + assert!(engine.validate_mapping_data(&json!({ "rule": "default", "groups": ["a"] }))); + + for rule in original_rules(&permissions) { + assert!(engine.validate_mapping_data(&rule), "{rule}"); + } + assert!(engine.validate_mapping_data(&json!({ "rule": "default" }))); + assert!( + engine + .validate_mapping_data(&json!({ "rule": "email_domain", "domain": "example.com" })) + ); + } fn group(name: &str) -> AccessGroup { AccessGroup { @@ -193,6 +277,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, } } diff --git a/v-api/src/permissions.rs b/v-api/src/permissions.rs index 5e39d57b..60b70c91 100644 --- a/v-api/src/permissions.rs +++ b/v-api/src/permissions.rs @@ -22,3 +22,128 @@ impl VAppPermissionResponse for T where T: Permission {} #[partial(VPermissionResponse, attributes(#[serde(tag = "kind", content = "value")]))] #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)] pub enum VPermission {} + +#[cfg(test)] +mod tests { + use newtype_uuid::TypedUuid; + use std::collections::{BTreeSet, HashSet}; + use v_model::permissions::{PermissionStorage, Permissions}; + + use super::VPermission; + + /// Only permissions whose own field carries a set of values are split. Permissions that are + /// relative to their holder stay whole. + #[test] + fn only_value_sets_are_expanded() { + let (a, b) = (TypedUuid::new_v4(), TypedUuid::new_v4()); + + let expanded = VPermission::ManageGroups(BTreeSet::from([a, b])) + .expand_value() + .unwrap(); + assert_eq!(2, expanded.len()); + assert!(expanded.contains(&VPermission::ManageGroup(a))); + assert!(expanded.contains(&VPermission::ManageGroup(b))); + + for relative in [ + VPermission::GetApiUserSelf, + VPermission::ManageApiUsersAssigned, + VPermission::GetGroupsJoined, + VPermission::ManageGroupsAll, + VPermission::ManageGroup(a), + ] { + assert_eq!(None, relative.expand_value(), "{relative:?} was expanded"); + } + } + + /// A set is granted value by value, so it can be assembled from separate holdings but not + /// from holdings that miss any value + #[test] + fn value_sets_are_granted_per_value() { + let (a, b, c) = ( + TypedUuid::new_v4(), + TypedUuid::new_v4(), + TypedUuid::new_v4(), + ); + let held: Permissions = vec![ + VPermission::ManageGroup(a), + VPermission::ManageGroups(BTreeSet::from([b])), + ] + .into(); + + assert!(held.can_grant(&VPermission::ManageGroups(BTreeSet::from([a, b])))); + assert!(!held.can_grant(&VPermission::ManageGroups(BTreeSet::from([a, c])))); + + let all: Permissions = vec![VPermission::ManageGroupsAll].into(); + assert!(all.can_grant(&VPermission::ManageGroups(BTreeSet::from([a, c])))); + } + + /// Removing one value from a stored set keeps the other values of that set + #[test] + fn removing_a_value_keeps_the_rest_of_its_set() { + let (a, b) = (TypedUuid::new_v4(), TypedUuid::new_v4()); + let stored: Permissions = vec![ + VPermission::ManageGroups(BTreeSet::from([a, b])), + VPermission::CreateGroup, + ] + .into(); + + let remaining = VPermission::contract(&stored.without(&VPermission::ManageGroup(a))); + + assert!(remaining.can(&VPermission::ManageGroup(b))); + assert!(!remaining.can(&VPermission::ManageGroup(a))); + assert!(remaining.can(&VPermission::CreateGroup)); + } + + /// Permissions relative to their holder are stored and removed as written, never turned into + /// the specific values they would resolve to + #[test] + fn relative_permissions_are_kept_as_written() { + let stored: Permissions = + vec![VPermission::GetApiUserSelf, VPermission::GetGroupsJoined].into(); + + let remaining = VPermission::contract(&stored.without(&VPermission::CreateGroup)); + assert!(remaining.iter().any(|p| p == &VPermission::GetApiUserSelf)); + assert!(remaining.iter().any(|p| p == &VPermission::GetGroupsJoined)); + + let remaining = VPermission::contract(&stored.without(&VPermission::GetApiUserSelf)); + assert!(!remaining.iter().any(|p| p == &VPermission::GetApiUserSelf)); + assert!(remaining.iter().any(|p| p == &VPermission::GetGroupsJoined)); + } + + /// Without an actor the permissions that need one resolve to nothing, while value sets and + /// aliases of the given permissions still resolve + #[test] + fn expanding_without_an_actor() { + let client = TypedUuid::new_v4(); + let group = TypedUuid::new_v4(); + let held: Permissions = vec![ + VPermission::GetApiUserSelf, + VPermission::GetGroupsJoined, + VPermission::ManageGroups(BTreeSet::from([group])), + VPermission::GetOAuthClientsAssigned, + VPermission::GetOAuthClient(client), + ] + .into(); + + let expanded = VPermission::expand(&held, None, Some(&held), &Default::default()); + + assert_eq!( + HashSet::from([ + VPermission::ManageGroup(group), + VPermission::GetOAuthClient(client), + ]), + expanded.into_iter().collect::>() + ); + } + + /// A permission over one specific group is stored as it was granted. It is never widened + /// into the permission over every group the holder has joined. + #[test] + fn a_single_group_grant_is_kept_as_written() { + let group = TypedUuid::new_v4(); + let stored = VPermission::contract(&vec![VPermission::GetGroup(group)].into()); + + assert!(stored.can(&VPermission::GetGroup(group))); + assert!(!stored.iter().any(|p| p == &VPermission::GetGroupsJoined)); + } +} diff --git a/v-api/tests/endpoint_macros.rs b/v-api/tests/endpoint_macros.rs index 930f67d0..3c07b243 100644 --- a/v-api/tests/endpoint_macros.rs +++ b/v-api/tests/endpoint_macros.rs @@ -90,12 +90,19 @@ fn system_endpoints_are_registered() { "/api-user/{user_id}/token/{api_key_id}", "/group", "/group/{group_id}", + "/group/{group_id}/permission", "/login/magic/{channel}/send", "/login/oauth/{provider}/code/token", "/login/oauth/{provider}/device", "/magic/client", "/mapper", "/oauth/client/{client_id}/secret", + "/oauth/client/{client_id}/service-account/permission", + "/oauth/client/{client_id}/service-account/token", + "/oauth/client/{client_id}/service-account/token/{token_id}", + "/oauth/client/{client_id}/service-account/key", + "/oauth/client/{client_id}/service-account/key/{key_id}", + "/oauth/token", "/self", ] { assert!(paths.contains(expected), "{expected} was not registered"); diff --git a/v-model/Cargo.toml b/v-model/Cargo.toml index 72370433..08200a19 100644 --- a/v-model/Cargo.toml +++ b/v-model/Cargo.toml @@ -13,6 +13,7 @@ sagas = ["steno"] [dependencies] async-bb8-diesel = { workspace = true } async-trait = { workspace = true } +base64 = { workspace = true } bb8 = { workspace = true } chrono = { workspace = true, features = ["serde"] } diesel = { workspace = true, features = ["chrono", "uuid", "serde_json"] } diff --git a/v-model/migrations/2026-10-20-045817_oauth_client_credentials/down.sql b/v-model/migrations/2026-10-20-045817_oauth_client_credentials/down.sql new file mode 100644 index 00000000..4ea1e69d --- /dev/null +++ b/v-model/migrations/2026-10-20-045817_oauth_client_credentials/down.sql @@ -0,0 +1,4 @@ +DROP TABLE oauth_client_assertion; +DROP TABLE oauth_client_key; +DROP TABLE service_account_token; +DROP TABLE service_account; diff --git a/v-model/migrations/2026-10-20-045817_oauth_client_credentials/up.sql b/v-model/migrations/2026-10-20-045817_oauth_client_credentials/up.sql new file mode 100644 index 00000000..21a8b390 --- /dev/null +++ b/v-model/migrations/2026-10-20-045817_oauth_client_credentials/up.sql @@ -0,0 +1,51 @@ +-- The permissions an OAuth client holds when it acts as a service account through client +-- credentials. The id is the id of the client. A client without a row holds no permissions, so a +-- row is only written once a permission is first granted. The generation is incremented by every +-- write, and permission changes are only written when it still matches the value that was read. +CREATE TABLE service_account( + id UUID PRIMARY KEY REFERENCES oauth_client (id), + permissions JSONB NOT NULL, + generation BIGINT NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +SELECT diesel_manage_updated_at('service_account'); + +-- Access tokens issued to OAuth clients acting as service accounts. They are kept apart from the +-- access tokens issued to users so that a token can only ever be resolved to the kind of +-- principal it was issued for. +CREATE TABLE service_account_token( + id UUID PRIMARY KEY, + oauth_client_id UUID REFERENCES oauth_client (id) NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + revoked_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +SELECT diesel_manage_updated_at('service_account_token'); + +CREATE INDEX service_account_token_oauth_client_id ON service_account_token (oauth_client_id); + +-- Public keys for verifying client assertions with. The thumbprint is unique across every row, +-- including deleted ones. Once registered a key can never be used by another client, even it +-- has been removed. +CREATE TABLE oauth_client_key( + id UUID PRIMARY KEY, + oauth_client_id UUID REFERENCES oauth_client (id) NOT NULL, + thumbprint VARCHAR NOT NULL UNIQUE, + jwk JSONB NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); + +-- Assertions that have been accepted. We keep assertions until their expiration has passed to +-- ensure they can not be replayed. +CREATE TABLE oauth_client_assertion( + oauth_client_id UUID REFERENCES oauth_client (id) NOT NULL, + jti VARCHAR NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (oauth_client_id, jti) +); + +CREATE INDEX oauth_client_assertion_expires_at ON oauth_client_assertion (expires_at); diff --git a/v-model/migrations/2026-10-20-164342_record_generation/down.sql b/v-model/migrations/2026-10-20-164342_record_generation/down.sql new file mode 100644 index 00000000..00e62385 --- /dev/null +++ b/v-model/migrations/2026-10-20-164342_record_generation/down.sql @@ -0,0 +1,2 @@ +ALTER TABLE access_groups DROP COLUMN generation; +ALTER TABLE api_user DROP COLUMN generation; diff --git a/v-model/migrations/2026-10-20-164342_record_generation/up.sql b/v-model/migrations/2026-10-20-164342_record_generation/up.sql new file mode 100644 index 00000000..149f4ad4 --- /dev/null +++ b/v-model/migrations/2026-10-20-164342_record_generation/up.sql @@ -0,0 +1,3 @@ +-- Add counters so that read then write updates can be performed without races +ALTER TABLE api_user ADD COLUMN generation BIGINT NOT NULL DEFAULT 0; +ALTER TABLE access_groups ADD COLUMN generation BIGINT NOT NULL DEFAULT 0; diff --git a/v-model/src/db.rs b/v-model/src/db.rs index 6c7c6506..8300c370 100644 --- a/v-model/src/db.rs +++ b/v-model/src/db.rs @@ -9,12 +9,14 @@ use serde_json::Value; use uuid::Uuid; use crate::{ + jwk::PublicJwk, permissions::Permissions, schema::{ access_groups, api_key, api_user, api_user_access_token, api_user_contact_email, api_user_provider, link_request, login_attempt, magic_link_attempt, magic_link_client, magic_link_client_redirect_uri, magic_link_client_secret, mapper, mapper_event, - oauth_client, oauth_client_redirect_uri, oauth_client_secret, + oauth_client, oauth_client_assertion, oauth_client_key, oauth_client_redirect_uri, + oauth_client_secret, service_account, service_account_token, }, schema_ext::MapperSource, schema_ext::{LoginAttemptState, MagicLinkAttemptState}, @@ -43,6 +45,7 @@ pub struct ApiUserModel { pub updated_at: DateTime, pub deleted_at: Option>, pub groups: Vec>, + pub generation: i64, } #[derive(Debug, Deserialize, Serialize, Queryable, Insertable)] @@ -113,6 +116,47 @@ pub struct OAuthClientModel { pub deleted_at: Option>, } +#[derive(Debug, Deserialize, Serialize, Queryable, Insertable)] +#[diesel(table_name = service_account)] +pub struct ServiceAccountModel { + pub id: Uuid, + pub permissions: Permissions, + pub generation: i64, + pub created_at: DateTime, + pub updated_at: DateTime, +} + +#[derive(Debug, Deserialize, Serialize, Queryable, Insertable)] +#[diesel(table_name = service_account_token)] +pub struct ServiceAccountTokenModel { + pub id: Uuid, + pub oauth_client_id: Uuid, + pub expires_at: DateTime, + pub revoked_at: Option>, + pub created_at: DateTime, + pub updated_at: DateTime, +} + +#[derive(Debug, Deserialize, Serialize, Queryable, Insertable)] +#[diesel(table_name = oauth_client_key)] +pub struct OAuthClientKeyModel { + pub id: Uuid, + pub oauth_client_id: Uuid, + pub thumbprint: String, + pub jwk: PublicJwk, + pub created_at: DateTime, + pub deleted_at: Option>, +} + +#[derive(Debug, Deserialize, Serialize, Queryable, Insertable)] +#[diesel(table_name = oauth_client_assertion)] +pub struct OAuthClientAssertionModel { + pub oauth_client_id: Uuid, + pub jti: String, + pub expires_at: DateTime, + pub created_at: DateTime, +} + #[derive(Debug, Deserialize, Serialize, Queryable, Insertable)] #[diesel(table_name = oauth_client_secret)] pub struct OAuthClientSecretModel { @@ -188,6 +232,7 @@ pub struct AccessGroupModel { pub created_at: DateTime, pub updated_at: DateTime, pub deleted_at: Option>, + pub generation: i64, } #[derive(Debug, Deserialize, Serialize, Queryable, QueryableByName, Insertable)] diff --git a/v-model/src/jwk.rs b/v-model/src/jwk.rs new file mode 100644 index 00000000..24d34c92 --- /dev/null +++ b/v-model/src/jwk.rs @@ -0,0 +1,180 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +use diesel::{ + AsExpression, FromSqlRow, + backend::Backend, + deserialize::{self, FromSql}, + pg::Pg, + serialize::{self, Output, ToSql}, + sql_types::Jsonb, +}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// A public key in JWK form. +#[derive( + Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, AsExpression, FromSqlRow, +)] +#[diesel(sql_type = Jsonb)] +#[serde(tag = "kty")] +#[non_exhaustive] +pub enum PublicJwk { + /// An Octet Key Pair key as defined by RFC 8037 §2 + #[serde(rename = "OKP")] + Okp(OkpPublicKey), +} + +impl PublicJwk { + /// An Ed25519 public key + pub fn ed25519(public_key: [u8; 32]) -> Self { + Self::Okp(OkpPublicKey::Ed25519 { x: public_key }) + } +} + +/// The public half of an Octet Key Pair key, selected by its `crv` member +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "crv", deny_unknown_fields)] +#[non_exhaustive] +pub enum OkpPublicKey { + #[non_exhaustive] + Ed25519 { + /// The 32 byte public key + #[serde(with = "base64url_bytes")] + #[schemars(with = "String")] + x: [u8; 32], + }, +} + +/// Encodes fixed size key material as unpadded base64url, as defined by RFC 7515 §2. +pub mod base64url_bytes { + use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; + use serde::{Deserialize, Deserializer, Serializer, de::Error}; + + pub fn serialize(bytes: &[u8; N], serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&URL_SAFE_NO_PAD.encode(bytes)) + } + + pub fn deserialize<'de, D, const N: usize>(deserializer: D) -> Result<[u8; N], D::Error> + where + D: Deserializer<'de>, + { + let encoded = String::deserialize(deserializer)?; + let decoded = URL_SAFE_NO_PAD + .decode(encoded.as_bytes()) + .map_err(D::Error::custom)?; + + <[u8; N]>::try_from(decoded.as_slice()).map_err(|_| { + D::Error::invalid_length( + decoded.len(), + &format!("{N} bytes of key material").as_str(), + ) + }) + } +} + +impl ToSql for PublicJwk { + fn to_sql(&self, out: &mut Output) -> serialize::Result { + let value = serde_json::to_value(self)?; + >::to_sql(&value, &mut out.reborrow()) + } +} + +impl FromSql for PublicJwk { + fn from_sql(bytes: ::RawValue<'_>) -> deserialize::Result { + let value = >::from_sql(bytes)?; + Ok(serde_json::from_value(value)?) + } +} + +#[cfg(test)] +mod tests { + use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; + use serde_json::{Value, json}; + + use super::{OkpPublicKey, PublicJwk}; + + const KEY: [u8; 32] = [7; 32]; + + fn parse(value: Value) -> Result { + serde_json::from_value(value) + } + + #[test] + fn serializes_as_an_rfc_8037_jwk() { + let jwk = serde_json::to_value(PublicJwk::ed25519(KEY)).unwrap(); + + assert_eq!( + json!({ "kty": "OKP", "crv": "Ed25519", "x": URL_SAFE_NO_PAD.encode(KEY) }), + jwk + ); + assert_eq!(PublicJwk::ed25519(KEY), parse(jwk).unwrap()); + } + + /// Members may arrive in any order, as JSON objects are unordered + #[test] + fn selects_the_key_by_type_and_curve() { + let jwk = + parse(json!({ "x": URL_SAFE_NO_PAD.encode(KEY), "crv": "Ed25519", "kty": "OKP" })) + .unwrap(); + + match jwk { + PublicJwk::Okp(OkpPublicKey::Ed25519 { x }) => assert_eq!(KEY, x), + } + } + + /// Unknown members are refused, which is what keeps a private key out of storage + #[test] + fn refuses_unknown_members() { + for (member, value) in [ + ("d", json!(URL_SAFE_NO_PAD.encode(KEY))), + ("x5c", json!(["certificate"])), + ("use", json!("sig")), + ] { + let mut jwk = + json!({ "kty": "OKP", "crv": "Ed25519", "x": URL_SAFE_NO_PAD.encode(KEY) }); + jwk[member] = value; + assert!(parse(jwk).is_err(), "accepted a key with {member}"); + } + } + + #[test] + fn refuses_unsupported_key_types_and_curves() { + for (kty, crv) in [ + ("EC", "P-256"), + ("RSA", "Ed25519"), + ("OKP", "Ed448"), + ("OKP", "X25519"), + ] { + let jwk = json!({ "kty": kty, "crv": crv, "x": URL_SAFE_NO_PAD.encode(KEY) }); + assert!(parse(jwk).is_err(), "accepted kty {kty} with crv {crv}"); + } + + assert!(parse(json!({ "crv": "Ed25519", "x": URL_SAFE_NO_PAD.encode(KEY) })).is_err()); + assert!(parse(json!({ "kty": "OKP", "x": URL_SAFE_NO_PAD.encode(KEY) })).is_err()); + } + + #[test] + fn refuses_ed25519_keys_that_are_not_32_bytes() { + for length in [31, 33, 57] { + let x = URL_SAFE_NO_PAD.encode(vec![7; length]); + let jwk = json!({ "kty": "OKP", "crv": "Ed25519", "x": x }); + assert!(parse(jwk).is_err(), "accepted a {length} byte key"); + } + } + + /// JWK members are unpadded base64url, so padded or standard base64 is refused + #[test] + fn refuses_other_base64_encodings() { + let padded = format!("{}=", URL_SAFE_NO_PAD.encode(KEY)); + let standard = base64::engine::general_purpose::STANDARD.encode([0xfb; 32]); + + for x in [padded, standard] { + let jwk = json!({ "kty": "OKP", "crv": "Ed25519", "x": x }); + assert!(parse(jwk).is_err(), "accepted {x}"); + } + } +} diff --git a/v-model/src/lib.rs b/v-model/src/lib.rs index 637bdd9c..b61601b9 100644 --- a/v-model/src/lib.rs +++ b/v-model/src/lib.rs @@ -7,8 +7,10 @@ use db::{ AccessGroupModel, ApiKeyModel, ApiUserAccessTokenModel, ApiUserContactEmailModel, ApiUserModel, ApiUserProviderModel, LinkRequestModel, LoginAttemptModel, MagicLinkAttemptModel, MagicLinkModel, MagicLinkRedirectUriModel, MagicLinkSecretModel, MapperEventModel, MapperModel, - OAuthClientModel, OAuthClientRedirectUriModel, OAuthClientSecretModel, + OAuthClientAssertionModel, OAuthClientKeyModel, OAuthClientModel, OAuthClientRedirectUriModel, + OAuthClientSecretModel, ServiceAccountModel, ServiceAccountTokenModel, }; +use jwk::PublicJwk; use newtype_uuid::{GenericUuid, TypedUuid, TypedUuidKind, TypedUuidTag}; use partial_struct::partial; use schema_ext::MagicLinkAttemptState; @@ -20,6 +22,7 @@ use thiserror::Error; use url::Url; pub mod db; +pub mod jwk; pub mod migrations; pub mod permissions; #[cfg(feature = "sagas")] @@ -77,6 +80,9 @@ pub struct ApiUser { pub updated_at: DateTime, #[partial(NewApiUser(skip))] pub deleted_at: Option>, + #[partial(NewApiUser(skip))] + #[serde(skip)] + pub generation: i64, } impl From> for ApiUser { @@ -92,6 +98,7 @@ impl From> for ApiUser { created_at: value.created_at, updated_at: value.updated_at, deleted_at: value.deleted_at, + generation: value.generation, } } } @@ -371,7 +378,7 @@ impl From for LoginAttempt { pkce_challenge_method: value.pkce_challenge_method, authz_code: value.authz_code, expires_at: value.expires_at, - error: None, + error: value.error, provider: value.provider, provider_pkce_verifier: value.provider_pkce_verifier, provider_authz_code: value.provider_authz_code, @@ -404,6 +411,8 @@ pub struct OAuthClient { #[partial(NewOAuthClient(skip))] pub redirect_uris: Vec, #[partial(NewOAuthClient(skip))] + pub keys: Vec, + #[partial(NewOAuthClient(skip))] pub created_at: DateTime, #[partial(NewOAuthClient(skip))] pub deleted_at: Option>, @@ -414,11 +423,13 @@ impl OAuthClient { client: OAuthClientModel, secrets: Vec, redirect_uris: Vec, + keys: Vec, ) -> Self { OAuthClient { id: TypedUuid::from_untyped_uuid(client.id), secrets, redirect_uris, + keys, created_at: client.created_at, deleted_at: client.deleted_at, } @@ -427,12 +438,77 @@ impl OAuthClient { impl From for OAuthClient { fn from(value: OAuthClientModel) -> Self { - OAuthClient { + OAuthClient::new(value, vec![], vec![], vec![]) + } +} + +/// The permissions an OAuth client holds when it acts as a service account through client +/// credentials. The id is the id of the client. +/// +/// A service account holds permissions directly. It belongs to no groups, and permissions that are +/// relative to whoever holds them do not apply to it. +#[partial(NewServiceAccount)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct ServiceAccount { + pub id: TypedUuid, + pub permissions: Permissions, + #[partial(NewServiceAccount(skip))] + pub created_at: DateTime, + #[partial(NewServiceAccount(skip))] + pub updated_at: DateTime, + /// Incremented by every write to the stored record. A change is only written when this still + /// matches the value that was read, so concurrent changes can not overwrite each other. It is + /// internal to storage and is not part of the API. + #[partial(NewServiceAccount(skip))] + #[serde(skip)] + pub generation: i64, +} + +impl From> for ServiceAccount { + fn from(value: ServiceAccountModel) -> Self { + ServiceAccount { id: TypedUuid::from_untyped_uuid(value.id), - secrets: vec![], - redirect_uris: vec![], + permissions: value.permissions, created_at: value.created_at, - deleted_at: value.deleted_at, + updated_at: value.updated_at, + generation: value.generation, + } + } +} + +#[derive(JsonSchema)] +pub enum ServiceAccountTokenId {} +impl TypedUuidKind for ServiceAccountTokenId { + fn tag() -> TypedUuidTag { + const TAG: TypedUuidTag = TypedUuidTag::new("service-account-token"); + TAG + } +} + +/// An access token issued to an OAuth client acting as a service account +#[partial(NewServiceAccountToken)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct ServiceAccountToken { + pub id: TypedUuid, + pub oauth_client_id: TypedUuid, + pub expires_at: DateTime, + #[partial(NewServiceAccountToken(skip))] + pub revoked_at: Option>, + #[partial(NewServiceAccountToken(skip))] + pub created_at: DateTime, + #[partial(NewServiceAccountToken(skip))] + pub updated_at: DateTime, +} + +impl From for ServiceAccountToken { + fn from(value: ServiceAccountTokenModel) -> Self { + ServiceAccountToken { + id: TypedUuid::from_untyped_uuid(value.id), + oauth_client_id: TypedUuid::from_untyped_uuid(value.oauth_client_id), + expires_at: value.expires_at, + revoked_at: value.revoked_at, + created_at: value.created_at, + updated_at: value.updated_at, } } } @@ -503,6 +579,63 @@ impl From for OAuthClientRedirectUri { } } +#[derive(JsonSchema)] +pub enum OAuthClientKeyId {} +impl TypedUuidKind for OAuthClientKeyId { + fn tag() -> TypedUuidTag { + const TAG: TypedUuidTag = TypedUuidTag::new("oauth-client-key"); + TAG + } +} + +#[partial(NewOAuthClientKey)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct OAuthClientKey { + pub id: TypedUuid, + pub oauth_client_id: TypedUuid, + /// The RFC 7638 §3 thumbprint of the key. Unique across all clients. + pub thumbprint: String, + pub jwk: PublicJwk, + #[partial(NewOAuthClientKey(skip))] + pub created_at: DateTime, + #[partial(NewOAuthClientKey(skip))] + pub deleted_at: Option>, +} + +impl From for OAuthClientKey { + fn from(value: OAuthClientKeyModel) -> Self { + OAuthClientKey { + id: TypedUuid::from_untyped_uuid(value.id), + oauth_client_id: TypedUuid::from_untyped_uuid(value.oauth_client_id), + thumbprint: value.thumbprint, + jwk: value.jwk, + created_at: value.created_at, + deleted_at: value.deleted_at, + } + } +} + +#[partial(NewOAuthClientAssertion)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct OAuthClientAssertion { + pub oauth_client_id: TypedUuid, + pub jti: String, + pub expires_at: DateTime, + #[partial(NewOAuthClientAssertion(skip))] + pub created_at: DateTime, +} + +impl From for OAuthClientAssertion { + fn from(value: OAuthClientAssertionModel) -> Self { + OAuthClientAssertion { + oauth_client_id: TypedUuid::from_untyped_uuid(value.oauth_client_id), + jti: value.jti, + expires_at: value.expires_at, + created_at: value.created_at, + } + } +} + #[derive(JsonSchema)] pub enum MagicLinkId {} impl TypedUuidKind for MagicLinkId { @@ -690,6 +823,9 @@ pub struct AccessGroup { pub updated_at: DateTime, #[partial(NewAccessGroup(skip))] pub deleted_at: Option>, + #[partial(NewAccessGroup(skip))] + #[serde(skip)] + pub generation: i64, } impl From> for AccessGroup { @@ -703,6 +839,7 @@ impl From> for AccessGroup { created_at: value.created_at, updated_at: value.updated_at, deleted_at: value.deleted_at, + generation: value.generation, } } } @@ -848,6 +985,7 @@ mod tests { created_at: Utc::now(), updated_at: Utc::now(), deleted_at: None, + generation: 0, }, email: Some(ApiUserContactEmail { id: TypedUuid::new_v4(), diff --git a/v-model/src/permissions.rs b/v-model/src/permissions.rs index 916dbd12..3e31dd79 100644 --- a/v-model/src/permissions.rs +++ b/v-model/src/permissions.rs @@ -23,7 +23,7 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use thiserror::Error; -use crate::{ApiUser, UserId}; +use crate::{ApiUser, OAuthClientId, UserId}; pub trait Permission: Clone + Debug + Serialize + DeserializeOwned + PartialEq + Send + Sync + 'static @@ -36,9 +36,18 @@ impl Permission for T where pub type ArcMap = HashMap>; +/// Who a caller is acting as +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Principal { + /// A person, signed in through a login provider or acting through one of their API keys + User(TypedUuid), + /// An OAuth client acting as itself through client credentials + ServiceAccount(TypedUuid), +} + #[derive(Debug, Clone)] pub struct Caller { - pub id: TypedUuid, + pub principal: Principal, pub permissions: Permissions, pub extensions: ArcMap, } @@ -47,8 +56,17 @@ impl Caller where T: Permission, { + /// The user the caller is acting as, or `None` when the caller is a service account + pub fn user_id(&self) -> Option> { + match self.principal { + Principal::User(id) => Some(id), + Principal::ServiceAccount(_) => None, + } + } + + /// Returns true if the caller is the given user. A service account is never a user. pub fn is(&self, id: &TypedUuid) -> bool { - &self.id == id + self.user_id().as_ref() == Some(id) } pub fn insert(&mut self, value: U) -> Option> @@ -107,13 +125,12 @@ where result } - /// Alias for [`can`](Self::can). A caller can grant any permission they hold. + /// Returns true if the caller could grant the target. See [`Permissions::can_grant`]. pub fn can_grant(&self, target: &T) -> bool { - self.can(target) + self.permissions.can_grant(target) } - /// Alias for [`all`](Self::all). A caller can grant a set of permissions if they hold - /// every one of them. + /// Returns true if the caller could grant every permission in the targets pub fn can_grant_all(&self, targets: &Permissions) -> bool { self.permissions.can_grant_all(targets) } @@ -122,7 +139,7 @@ where impl From> for Caller { fn from(value: Permissions) -> Self { Self { - id: TypedUuid::new_v4(), + principal: Principal::User(TypedUuid::new_v4()), permissions: value, extensions: HashMap::new(), } @@ -220,22 +237,57 @@ where } /// Returns true if any held permission implies the target, either by exact match - /// or through the permission hierarchy (e.g., an "All" variant implies specific instances). + /// or through a permission definition. pub fn can(&self, permission: &T) -> bool { let res = self.iter().any(|held| T::implies(held, permission)); tracing::trace!(available = ?self.0, requested = ?permission, result = ?res, "Permissions existence check"); res } - /// Alias for [`can`](Self::can). A permission set can grant any permission it holds. + /// Returns true if this set could grant the target to someone else. pub fn can_grant(&self, target: &T) -> bool { - self.can(target) + // We need to expand the target to verify that every permission it expresses is covered by + // this permission set. We can not use equality as this permission set may contain supersets + // for value carrying permissions compared to the target permission. + match target.expand_value() { + Some(values) => values.iter().all(|value| self.can(value)), + None => self.can(target), + } } - /// Alias for [`all`](Self::all). A permission set can grant a collection of permissions - /// if it holds every one of them. + /// Returns true if this set could grant every permission in the targets pub fn can_grant_all(&self, targets: &Permissions) -> bool { - targets.iter().all(|target| self.can(target)) + targets.iter().all(|target| self.can_grant(target)) + } + + /// Splits every permission that carries a set of values into one permission per value. + pub fn expand_values(&self) -> Permissions { + let mut expanded = Permissions::new(); + for permission in self.iter() { + match permission.expand_value() { + Some(values) => values.into_iter().for_each(|value| { + expanded.insert(value); + }), + None => { + expanded.insert(permission.clone()); + } + } + } + + expanded + } + + /// Returns this set with the target removed. + pub fn without(&self, target: &T) -> Permissions { + let removed = target + .expand_value() + .unwrap_or_else(|| vec![target.clone()]); + let mut remaining = self.expand_values(); + removed.iter().for_each(|value| { + remaining.remove(value); + }); + + remaining } } @@ -344,9 +396,12 @@ pub trait PermissionStorage { fn contract(_collection: &Permissions) -> Permissions where Self: Sized; + /// Resolves the permissions in a collection that are relative to whoever holds them. A caller + /// that is not a user has no actor, and permissions that refer to the actor's own user record + /// expand to nothing for them. fn expand( collection: &Permissions, - actor: &ApiUser, + actor: Option<&ApiUser>, actor_permissions: Option<&Permissions>, extensions: &ArcMap, ) -> Permissions @@ -359,4 +414,49 @@ pub trait PermissionStorage { fn implies(held: &Self, target: &Self) -> bool where Self: Sized; + + /// Splits a permission that carries a set of values into one permission per value. Returns + /// `None` for any permission that does not carry a set of values, which includes permissions + /// whose meaning is relative to whoever holds them. + fn expand_value(&self) -> Option> + where + Self: Sized, + { + None + } +} + +#[cfg(test)] +mod tests { + use newtype_uuid::{GenericUuid, TypedUuid}; + + use super::{Caller, Permissions, Principal}; + + fn caller(principal: Principal) -> Caller<()> { + Caller { + principal, + permissions: Permissions::default(), + extensions: Default::default(), + } + } + + #[test] + fn a_user_caller_is_that_user() { + let user_id = TypedUuid::new_v4(); + let user = caller(Principal::User(user_id)); + + assert_eq!(Some(user_id), user.user_id()); + assert!(user.is(&user_id)); + assert!(!user.is(&TypedUuid::new_v4())); + } + + /// A service account is never treated as a user, even one whose id has the same value + #[test] + fn a_service_account_is_never_a_user() { + let client_id = TypedUuid::new_v4(); + let service_account = caller(Principal::ServiceAccount(client_id)); + + assert_eq!(None, service_account.user_id()); + assert!(!service_account.is(&TypedUuid::from_untyped_uuid(client_id.into_untyped_uuid()))); + } } diff --git a/v-model/src/schema.rs b/v-model/src/schema.rs index 27ddbee1..664bae7a 100644 --- a/v-model/src/schema.rs +++ b/v-model/src/schema.rs @@ -20,6 +20,7 @@ diesel::table! { created_at -> Timestamptz, updated_at -> Timestamptz, deleted_at -> Nullable, + generation -> Int8, } } @@ -44,6 +45,7 @@ diesel::table! { updated_at -> Timestamptz, deleted_at -> Nullable, groups -> Array>, + generation -> Int8, } } @@ -205,6 +207,26 @@ diesel::table! { } } +diesel::table! { + oauth_client_assertion (oauth_client_id, jti) { + oauth_client_id -> Uuid, + jti -> Varchar, + expires_at -> Timestamptz, + created_at -> Timestamptz, + } +} + +diesel::table! { + oauth_client_key (id) { + id -> Uuid, + oauth_client_id -> Uuid, + thumbprint -> Varchar, + jwk -> Jsonb, + created_at -> Timestamptz, + deleted_at -> Nullable, + } +} + diesel::table! { oauth_client_redirect_uri (id) { id -> Uuid, @@ -225,6 +247,27 @@ diesel::table! { } } +diesel::table! { + service_account (id) { + id -> Uuid, + permissions -> Jsonb, + generation -> Int8, + created_at -> Timestamptz, + updated_at -> Timestamptz, + } +} + +diesel::table! { + service_account_token (id) { + id -> Uuid, + oauth_client_id -> Uuid, + expires_at -> Timestamptz, + revoked_at -> Nullable, + created_at -> Timestamptz, + updated_at -> Timestamptz, + } +} + #[cfg(feature = "sagas")] diesel::table! { sagas (saga_id) { @@ -257,8 +300,12 @@ diesel::joinable!(api_user_provider -> api_user (api_user_id)); diesel::joinable!(magic_link_attempt -> magic_link_client (magic_link_client_id)); diesel::joinable!(magic_link_client_redirect_uri -> magic_link_client (magic_link_client_id)); diesel::joinable!(magic_link_client_secret -> magic_link_client (magic_link_client_id)); +diesel::joinable!(oauth_client_assertion -> oauth_client (oauth_client_id)); +diesel::joinable!(oauth_client_key -> oauth_client (oauth_client_id)); diesel::joinable!(oauth_client_redirect_uri -> oauth_client (oauth_client_id)); diesel::joinable!(oauth_client_secret -> oauth_client (oauth_client_id)); +diesel::joinable!(service_account -> oauth_client (id)); +diesel::joinable!(service_account_token -> oauth_client (oauth_client_id)); #[cfg(feature = "sagas")] diesel::joinable!(saga_events -> sagas (saga_id)); @@ -279,6 +326,10 @@ diesel::allow_tables_to_appear_in_same_query!( mapper, mapper_event, oauth_client, + oauth_client_assertion, + oauth_client_key, oauth_client_redirect_uri, oauth_client_secret, + service_account, + service_account_token, ); diff --git a/v-model/src/storage/mod.rs b/v-model/src/storage/mod.rs index 0108b647..269147dd 100644 --- a/v-model/src/storage/mod.rs +++ b/v-model/src/storage/mod.rs @@ -7,6 +7,7 @@ use std::fmt::Debug; pub use async_bb8_diesel::{ConnectionError, PoolError}; use async_trait::async_trait; use bb8::RunError; +use chrono::{DateTime, Utc}; pub use diesel::result::Error as DbError; use diesel::result::{DatabaseErrorKind, Error as DieselError}; #[cfg(feature = "mock")] @@ -23,9 +24,11 @@ use crate::{ MapperId, MapperSource, NewAccessGroup, NewAccessToken, NewApiKey, NewApiUser, NewApiUserContactEmail, NewApiUserProvider, NewLinkRequest, NewLoginAttempt, NewMagicLink, NewMagicLinkAttempt, NewMagicLinkRedirectUri, NewMagicLinkSecret, NewMapper, NewMapperEvent, - NewOAuthClient, NewOAuthClientRedirectUri, NewOAuthClientSecret, OAuthClient, OAuthClientId, - OAuthClientRedirectUri, OAuthClientSecret, OAuthRedirectUriId, OAuthSecretId, - UserContactEmailId, UserId, UserProviderId, + NewOAuthClient, NewOAuthClientAssertion, NewOAuthClientKey, NewOAuthClientRedirectUri, + NewOAuthClientSecret, NewServiceAccount, NewServiceAccountToken, OAuthClient, + OAuthClientAssertion, OAuthClientId, OAuthClientKey, OAuthClientKeyId, OAuthClientRedirectUri, + OAuthClientSecret, OAuthRedirectUriId, OAuthSecretId, ServiceAccount, ServiceAccountToken, + ServiceAccountTokenId, UserContactEmailId, UserId, UserProviderId, schema_ext::{LoginAttemptState, MagicLinkAttemptState}, }; @@ -144,7 +147,12 @@ pub trait ApiUserStore { filter: ApiUserFilter, pagination: &ListPagination, ) -> Result>, StoreError>; - async fn upsert(&self, api_user: NewApiUser) -> Result, StoreError>; + async fn create(&self, api_user: NewApiUser) -> Result, StoreError>; + async fn update( + &self, + api_user: NewApiUser, + expected_generation: i64, + ) -> Result>, StoreError>; async fn delete(&self, id: &TypedUuid) -> Result>, StoreError>; } @@ -343,6 +351,108 @@ pub trait OAuthClientRedirectUriStore { ) -> Result, StoreError>; } +#[cfg_attr(feature = "mock", automock)] +#[async_trait] +pub trait ServiceAccountStore { + /// The service account of an OAuth client, or `None` when the client has never been granted + /// a permission + async fn get( + &self, + id: &TypedUuid, + ) -> Result>, StoreError>; + /// Store the first permissions of a service account. Fails with [`StoreError::Conflict`] when + /// the service account already exists, which means a concurrent change wrote it first. + async fn create(&self, account: NewServiceAccount) -> Result, StoreError>; + /// Write the service account's permissions only if its generation is still + /// `expected_generation`. Returns `None` without writing when another write has landed since + /// the read. + async fn update( + &self, + account: NewServiceAccount, + expected_generation: i64, + ) -> Result>, StoreError>; +} + +#[derive(Debug, Default, PartialEq)] +pub struct ServiceAccountTokenFilter { + pub oauth_client_id: Option>>, + /// Include tokens that have been revoked + pub revoked: bool, + /// Include tokens whose expiration has passed + pub expired: bool, +} + +#[cfg_attr(feature = "mock", automock)] +#[async_trait] +pub trait ServiceAccountTokenStore { + /// A token by its id. Revoked tokens are only returned when `revoked` is true. + async fn get( + &self, + id: &TypedUuid, + revoked: bool, + ) -> Result, StoreError>; + /// Tokens matching the filter, newest first + async fn list( + &self, + filter: ServiceAccountTokenFilter, + pagination: &ListPagination, + ) -> Result, StoreError>; + /// Record a newly issued token. Fails with [`StoreError::Conflict`] when a token with the same + /// id already exists. + async fn create( + &self, + token: NewServiceAccountToken, + ) -> Result; + /// Revoke a token. Returns `None` when there is no unrevoked token with the id. + async fn revoke( + &self, + id: &TypedUuid, + ) -> Result, StoreError>; +} + +#[derive(Debug, Default)] +pub struct OAuthClientKeyFilter { + pub id: Option>>, + pub oauth_client_id: Option>>, + pub thumbprint: Option>, + pub deleted: bool, +} + +#[cfg_attr(feature = "mock", automock)] +#[async_trait] +pub trait OAuthClientKeyStore { + async fn get( + &self, + id: &TypedUuid, + deleted: bool, + ) -> Result, StoreError>; + async fn list( + &self, + filter: OAuthClientKeyFilter, + pagination: &ListPagination, + ) -> Result, StoreError>; + /// Store a new key. A key whose thumbprint is already registered to any client, even as a + /// deleted key must fail with [`StoreError::Conflict`]. + async fn insert(&self, key: NewOAuthClientKey) -> Result; + async fn delete( + &self, + id: &TypedUuid, + ) -> Result, StoreError>; +} + +#[cfg_attr(feature = "mock", automock)] +#[async_trait] +pub trait OAuthClientAssertionStore { + /// Record an accepted assertion. This must fail with [`StoreError::Conflict`] when an + /// assertion with the same jti, for a given client, already exists. + async fn record( + &self, + assertion: NewOAuthClientAssertion, + ) -> Result; + /// Returning how many assertions were removed. + async fn delete_expired(&self, before: DateTime) -> Result; +} + #[derive(Debug, Default)] pub struct MagicLinkFilter { pub id: Option>>, @@ -443,7 +553,18 @@ pub trait AccessGroupStore { filter: AccessGroupFilter, pagination: &ListPagination, ) -> Result>, StoreError>; + /// Store a group. When a group with the same id already exists only its permissions are + /// replaced, and its name is kept. async fn upsert(&self, group: &NewAccessGroup) -> Result, StoreError>; + /// Write the group's permissions only if its generation is still `expected_generation`. + /// + /// A group's name is never changed after it is created. Mappers resolve groups by name, so + /// renaming a group would silently change which users mappers place into it. + async fn update( + &self, + group: &NewAccessGroup, + expected_generation: i64, + ) -> Result>, StoreError>; async fn delete( &self, id: &TypedUuid, diff --git a/v-model/src/storage/postgres.rs b/v-model/src/storage/postgres.rs index 995453fd..9f4c7e82 100644 --- a/v-model/src/storage/postgres.rs +++ b/v-model/src/storage/postgres.rs @@ -5,7 +5,7 @@ use async_bb8_diesel::{AsyncRunQueryDsl, ConnectionError, ConnectionManager}; use async_trait::async_trait; use bb8::Pool; -use chrono::Utc; +use chrono::{DateTime, Utc}; use diesel::{ ExpressionMethods, OptionalExtension as OptionalExtension2, PgArrayExpressionMethods, insert_into, pg::PgConnection, query_dsl::QueryDsl, update, upsert::excluded, @@ -24,22 +24,26 @@ use crate::{ MapperEvent, MapperId, NewAccessGroup, NewAccessToken, NewApiKey, NewApiUser, NewApiUserContactEmail, NewApiUserProvider, NewLinkRequest, NewLoginAttempt, NewMagicLink, NewMagicLinkAttempt, NewMagicLinkRedirectUri, NewMagicLinkSecret, NewMapper, NewMapperEvent, - NewOAuthClient, NewOAuthClientRedirectUri, NewOAuthClientSecret, OAuthClient, OAuthClientId, - OAuthClientRedirectUri, OAuthClientSecret, OAuthRedirectUriId, OAuthSecretId, - UserContactEmailId, UserId, UserProviderId, + NewOAuthClient, NewOAuthClientAssertion, NewOAuthClientKey, NewOAuthClientRedirectUri, + NewOAuthClientSecret, NewServiceAccount, NewServiceAccountToken, OAuthClient, + OAuthClientAssertion, OAuthClientId, OAuthClientKey, OAuthClientKeyId, OAuthClientRedirectUri, + OAuthClientSecret, OAuthRedirectUriId, OAuthSecretId, ServiceAccount, ServiceAccountToken, + ServiceAccountTokenId, UserContactEmailId, UserId, UserProviderId, db::{ AccessGroupModel, ApiKeyModel, ApiUserAccessTokenModel, ApiUserContactEmailModel, ApiUserModel, ApiUserProviderModel, LinkRequestModel, LoginAttemptModel, MagicLinkAttemptModel, MagicLinkModel, MagicLinkRedirectUriModel, MagicLinkSecretModel, - MapperEventModel, MapperModel, OAuthClientModel, OAuthClientRedirectUriModel, - OAuthClientSecretModel, + MapperEventModel, MapperModel, OAuthClientAssertionModel, OAuthClientKeyModel, + OAuthClientModel, OAuthClientRedirectUriModel, OAuthClientSecretModel, ServiceAccountModel, + ServiceAccountTokenModel, }, permissions::Permission, schema::{ access_groups, api_key, api_user, api_user_access_token, api_user_contact_email, api_user_provider, link_request, login_attempt, magic_link_attempt, magic_link_client, magic_link_client_redirect_uri, magic_link_client_secret, mapper, mapper_event, - oauth_client, oauth_client_redirect_uri, oauth_client_secret, + oauth_client, oauth_client_assertion, oauth_client_key, oauth_client_redirect_uri, + oauth_client_secret, service_account, service_account_token, }, schema_ext::{LoginAttemptState, MagicLinkAttemptState}, storage::{LinkRequestFilter, LinkRequestStore, StoreError}, @@ -51,8 +55,9 @@ use super::{ ApiUserProviderFilter, ApiUserProviderStore, ApiUserStore, ListPagination, LoginAttemptFilter, LoginAttemptStore, MagicLinkAttemptFilter, MagicLinkAttemptStore, MagicLinkFilter, MagicLinkRedirectUriStore, MagicLinkSecretStore, MagicLinkStore, MapperEventFilter, - MapperEventStore, MapperFilter, MapperStore, OAuthClientFilter, OAuthClientRedirectUriStore, - OAuthClientSecretStore, OAuthClientStore, + MapperEventStore, MapperFilter, MapperStore, OAuthClientAssertionStore, OAuthClientFilter, + OAuthClientKeyFilter, OAuthClientKeyStore, OAuthClientRedirectUriStore, OAuthClientSecretStore, + OAuthClientStore, ServiceAccountStore, ServiceAccountTokenFilter, ServiceAccountTokenStore, }; pub type DbPool = Pool>; @@ -209,10 +214,7 @@ where Ok(users) } - #[instrument(skip(self), fields(id = ?user.id, permissions = ?user.permissions, groups = ?user.groups))] - async fn upsert(&self, user: NewApiUser) -> Result, StoreError> { - tracing::trace!("Upserting user"); - + async fn create(&self, user: NewApiUser) -> Result, StoreError> { insert_into(api_user::dsl::api_user) .values(( api_user::id.eq(user.id.into_untyped_uuid()), @@ -223,24 +225,46 @@ where .map(|g| g.into_untyped_uuid()) .collect::>()), )) - .on_conflict(api_user::id) - .do_update() + .execute_async(&*self.pool.get().await?) + .await?; + + Ok(ApiUserStore::get(self, &user.id, false).await?.unwrap()) + } + + async fn update( + &self, + user: NewApiUser, + expected_generation: i64, + ) -> Result>, StoreError> { + let updated = update(api_user::dsl::api_user) + .filter(api_user::id.eq(user.id.into_untyped_uuid())) + .filter(api_user::generation.eq(expected_generation)) + .filter(api_user::deleted_at.is_null()) .set(( - api_user::permissions.eq(excluded(api_user::permissions)), - api_user::groups.eq(excluded(api_user::groups)), + api_user::permissions.eq(user.permissions.clone()), + api_user::groups.eq(user + .groups + .into_iter() + .map(|g| g.into_untyped_uuid()) + .collect::>()), + api_user::generation.eq(api_user::generation + 1), )) .execute_async(&*self.pool.get().await?) .await?; - tracing::trace!("Upserted api user"); - - Ok(ApiUserStore::get(self, &user.id, false).await?.unwrap()) + match updated { + 0 => Ok(None), + _ => ApiUserStore::get(self, &user.id, false).await, + } } async fn delete(&self, id: &TypedUuid) -> Result>, StoreError> { let _ = update(api_user::dsl::api_user) .filter(api_user::id.eq(id.into_untyped_uuid())) - .set(api_user::deleted_at.eq(Utc::now())) + .set(( + api_user::deleted_at.eq(Utc::now()), + api_user::generation.eq(api_user::generation + 1), + )) .execute_async(&*self.pool.get().await?) .await?; @@ -855,6 +879,7 @@ impl OAuthClientStore for PostgresStore { let mut query = oauth_client::dsl::oauth_client .left_join(oauth_client_secret::table) .left_join(oauth_client_redirect_uri::table) + .left_join(oauth_client_key::table) .into_boxed(); let OAuthClientFilter { id, deleted } = filter; @@ -875,18 +900,20 @@ impl OAuthClientStore for PostgresStore { OAuthClientModel, Option, Option, + Option, )>(&*self.pool.get().await?) .await? .into_iter() .fold( BTreeMap::new(), - |mut clients, (client, secret, redirect)| { - // The joins produce a row per secret x redirect uri combination, so each - // list is keyed by id to drop the duplicate entries + |mut clients, (client, secret, redirect, key)| { + // The joins produce a row per secret x redirect uri x key combination, so + // each list is keyed by id to drop the duplicate entries let value = clients.entry(client.id).or_insert(( client, BTreeMap::::new(), BTreeMap::::new(), + BTreeMap::::new(), )); // Only include secrets that have not been deleted @@ -906,15 +933,23 @@ impl OAuthClientStore for PostgresStore { .or_insert_with(|| redirect.into()); } + // Only include keys that have not been deleted + if let Some(key) = key + && key.deleted_at.is_none() + { + value.3.entry(key.id).or_insert_with(|| key.into()); + } + clients }, ) .into_iter() - .map(|(_, (client, secrets, redirect_uris))| { + .map(|(_, (client, secrets, redirect_uris, keys))| { OAuthClient::new( client, secrets.into_values().collect(), redirect_uris.into_values().collect(), + keys.into_values().collect(), ) }) .skip(pagination.offset as usize) @@ -947,6 +982,281 @@ impl OAuthClientStore for PostgresStore { } } +#[async_trait] +impl ServiceAccountStore for PostgresStore +where + T: Permission, +{ + async fn get( + &self, + id: &TypedUuid, + ) -> Result>, StoreError> { + let account = service_account::dsl::service_account + .filter(service_account::id.eq(id.into_untyped_uuid())) + .get_result_async::>(&*self.pool.get().await?) + .await + .optional()?; + + Ok(account.map(|account| account.into())) + } + + async fn create(&self, account: NewServiceAccount) -> Result, StoreError> { + let account_m: ServiceAccountModel = insert_into(service_account::dsl::service_account) + .values(( + service_account::id.eq(account.id.into_untyped_uuid()), + service_account::permissions.eq(account.permissions), + )) + .get_result_async(&*self.pool.get().await?) + .await?; + + Ok(account_m.into()) + } + + async fn update( + &self, + account: NewServiceAccount, + expected_generation: i64, + ) -> Result>, StoreError> { + let account_m: Option> = + update(service_account::dsl::service_account) + .filter(service_account::id.eq(account.id.into_untyped_uuid())) + .filter(service_account::generation.eq(expected_generation)) + .set(( + service_account::permissions.eq(account.permissions), + service_account::generation.eq(service_account::generation + 1), + )) + .get_result_async(&*self.pool.get().await?) + .await + .optional()?; + + Ok(account_m.map(|account| account.into())) + } +} + +#[async_trait] +impl ServiceAccountTokenStore for PostgresStore { + async fn get( + &self, + id: &TypedUuid, + revoked: bool, + ) -> Result, StoreError> { + let mut query = service_account_token::dsl::service_account_token + .into_boxed() + .filter(service_account_token::id.eq(id.into_untyped_uuid())); + + if !revoked { + query = query.filter(service_account_token::revoked_at.is_null()); + } + + let token = query + .get_result_async::(&*self.pool.get().await?) + .await + .optional()?; + + Ok(token.map(|token| token.into())) + } + + async fn list( + &self, + filter: ServiceAccountTokenFilter, + pagination: &ListPagination, + ) -> Result, StoreError> { + let mut query = service_account_token::dsl::service_account_token.into_boxed(); + + let ServiceAccountTokenFilter { + oauth_client_id, + revoked, + expired, + } = filter; + + if let Some(oauth_client_id) = oauth_client_id { + query = query.filter( + service_account_token::oauth_client_id + .eq_any(oauth_client_id.into_iter().map(|id| id.into_untyped_uuid())), + ); + } + + if !revoked { + query = query.filter(service_account_token::revoked_at.is_null()); + } + + if !expired { + query = query.filter(service_account_token::expires_at.gt(Utc::now())); + } + + let tokens = query + .offset(pagination.offset) + .limit(pagination.limit) + .order(service_account_token::created_at.desc()) + .get_results_async::(&*self.pool.get().await?) + .await?; + + Ok(tokens.into_iter().map(|token| token.into()).collect()) + } + + async fn create( + &self, + token: NewServiceAccountToken, + ) -> Result { + let token_m: ServiceAccountTokenModel = + insert_into(service_account_token::dsl::service_account_token) + .values(( + service_account_token::id.eq(token.id.into_untyped_uuid()), + service_account_token::oauth_client_id + .eq(token.oauth_client_id.into_untyped_uuid()), + service_account_token::expires_at.eq(token.expires_at), + )) + .get_result_async(&*self.pool.get().await?) + .await?; + + Ok(token_m.into()) + } + + async fn revoke( + &self, + id: &TypedUuid, + ) -> Result, StoreError> { + let token_m: Option = + update(service_account_token::dsl::service_account_token) + .filter(service_account_token::id.eq(id.into_untyped_uuid())) + .filter(service_account_token::revoked_at.is_null()) + .set(service_account_token::revoked_at.eq(Utc::now())) + .get_result_async(&*self.pool.get().await?) + .await + .optional()?; + + Ok(token_m.map(|token| token.into())) + } +} + +#[async_trait] +impl OAuthClientKeyStore for PostgresStore { + async fn get( + &self, + id: &TypedUuid, + deleted: bool, + ) -> Result, StoreError> { + let key = OAuthClientKeyStore::list( + self, + OAuthClientKeyFilter { + id: Some(vec![*id]), + deleted, + ..Default::default() + }, + &ListPagination::default().limit(1), + ) + .await?; + + Ok(key.into_iter().nth(0)) + } + + async fn list( + &self, + filter: OAuthClientKeyFilter, + pagination: &ListPagination, + ) -> Result, StoreError> { + let mut query = oauth_client_key::dsl::oauth_client_key.into_boxed(); + + let OAuthClientKeyFilter { + id, + oauth_client_id, + thumbprint, + deleted, + } = filter; + + if let Some(id) = id { + query = query.filter( + oauth_client_key::id.eq_any(id.into_iter().map(|key| key.into_untyped_uuid())), + ); + } + + if let Some(oauth_client_id) = oauth_client_id { + query = query.filter( + oauth_client_key::oauth_client_id.eq_any( + oauth_client_id + .into_iter() + .map(|client| client.into_untyped_uuid()), + ), + ); + } + + if let Some(thumbprint) = thumbprint { + query = query.filter(oauth_client_key::thumbprint.eq_any(thumbprint)); + } + + if !deleted { + query = query.filter(oauth_client_key::deleted_at.is_null()); + } + + let results = query + .offset(pagination.offset) + .limit(pagination.limit) + .order(oauth_client_key::created_at.desc()) + .get_results_async::(&*self.pool.get().await?) + .await?; + + Ok(results.into_iter().map(|key| key.into()).collect()) + } + + async fn insert(&self, key: NewOAuthClientKey) -> Result { + let key_m: OAuthClientKeyModel = insert_into(oauth_client_key::dsl::oauth_client_key) + .values(( + oauth_client_key::id.eq(key.id.into_untyped_uuid()), + oauth_client_key::oauth_client_id.eq(key.oauth_client_id.into_untyped_uuid()), + oauth_client_key::thumbprint.eq(key.thumbprint), + oauth_client_key::jwk.eq(key.jwk), + )) + .get_result_async(&*self.pool.get().await?) + .await?; + + Ok(key_m.into()) + } + + async fn delete( + &self, + id: &TypedUuid, + ) -> Result, StoreError> { + let _ = update(oauth_client_key::dsl::oauth_client_key) + .filter(oauth_client_key::id.eq(id.into_untyped_uuid())) + .filter(oauth_client_key::deleted_at.is_null()) + .set(oauth_client_key::deleted_at.eq(Utc::now())) + .execute_async(&*self.pool.get().await?) + .await?; + + OAuthClientKeyStore::get(self, id, true).await + } +} + +#[async_trait] +impl OAuthClientAssertionStore for PostgresStore { + async fn record( + &self, + assertion: NewOAuthClientAssertion, + ) -> Result { + let assertion_m: OAuthClientAssertionModel = + insert_into(oauth_client_assertion::dsl::oauth_client_assertion) + .values(( + oauth_client_assertion::oauth_client_id + .eq(assertion.oauth_client_id.into_untyped_uuid()), + oauth_client_assertion::jti.eq(assertion.jti), + oauth_client_assertion::expires_at.eq(assertion.expires_at), + )) + .get_result_async(&*self.pool.get().await?) + .await?; + + Ok(assertion_m.into()) + } + + async fn delete_expired(&self, before: DateTime) -> Result { + Ok( + diesel::delete(oauth_client_assertion::dsl::oauth_client_assertion) + .filter(oauth_client_assertion::expires_at.lt(before)) + .execute_async(&*self.pool.get().await?) + .await?, + ) + } +} + #[async_trait] impl OAuthClientSecretStore for PostgresStore { async fn upsert(&self, secret: NewOAuthClientSecret) -> Result { @@ -1438,8 +1748,9 @@ where .on_conflict(access_groups::id) .do_update() .set(( - access_groups::name.eq(excluded(access_groups::name)), + // The name of an existing group is never changed, see AccessGroupStore::update access_groups::permissions.eq(excluded(access_groups::permissions)), + access_groups::generation.eq(access_groups::generation + 1), )) .get_result_async(&*self.pool.get().await?) .await?; @@ -1447,13 +1758,36 @@ where Ok(group_m.into()) } + async fn update( + &self, + group: &NewAccessGroup, + expected_generation: i64, + ) -> Result>, StoreError> { + let group_m: Option> = update(access_groups::dsl::access_groups) + .filter(access_groups::id.eq(group.id.into_untyped_uuid())) + .filter(access_groups::generation.eq(expected_generation)) + .filter(access_groups::deleted_at.is_null()) + .set(( + access_groups::permissions.eq(group.permissions.clone()), + access_groups::generation.eq(access_groups::generation + 1), + )) + .get_result_async(&*self.pool.get().await?) + .await + .optional()?; + + Ok(group_m.map(|group| group.into())) + } + async fn delete( &self, id: &TypedUuid, ) -> Result>, StoreError> { let _ = update(access_groups::dsl::access_groups) .filter(access_groups::id.eq(id.into_untyped_uuid())) - .set(access_groups::deleted_at.eq(Utc::now())) + .set(( + access_groups::deleted_at.eq(Utc::now()), + access_groups::generation.eq(access_groups::generation + 1), + )) .execute_async(&*self.pool.get().await?) .await?; diff --git a/v-model/tests/postgres.rs b/v-model/tests/postgres.rs index b28560a8..a4b4a196 100644 --- a/v-model/tests/postgres.rs +++ b/v-model/tests/postgres.rs @@ -16,12 +16,18 @@ use serde::{Deserialize, Serialize}; use std::ops::{Add, Sub}; use uuid::Uuid; use v_model::{ - NewApiKey, NewApiUser, NewMagicLink, NewMagicLinkAttempt, NewMapper, UserId, + NewAccessGroup, NewApiKey, NewApiUser, NewLoginAttempt, NewMagicLink, NewMagicLinkAttempt, + NewMapper, NewOAuthClient, NewOAuthClientAssertion, NewOAuthClientKey, NewServiceAccount, + NewServiceAccountToken, OAuthClientId, UserId, + jwk::PublicJwk, migrations::run_migrations_quiet, - schema_ext::MagicLinkAttemptState, + schema_ext::{LoginAttemptState, MagicLinkAttemptState}, storage::{ - ApiKeyFilter, ApiKeyStore, ApiUserFilter, ApiUserStore, ListPagination, - MagicLinkAttemptStore, MagicLinkStore, MapperStore, postgres::PostgresStore, + AccessGroupStore, ApiKeyFilter, ApiKeyStore, ApiUserFilter, ApiUserStore, ListPagination, + LoginAttemptStore, MagicLinkAttemptStore, MagicLinkStore, MapperStore, + OAuthClientAssertionStore, OAuthClientKeyFilter, OAuthClientKeyStore, OAuthClientStore, + ServiceAccountStore, ServiceAccountTokenFilter, ServiceAccountTokenStore, StoreError, + postgres::PostgresStore, }, }; @@ -46,7 +52,7 @@ impl v_model::permissions::PermissionStorage for TestPermission { } fn expand( collection: &v_model::Permissions, - _actor: &v_model::ApiUser, + _actor: Option<&v_model::ApiUser>, _actor_permissions: Option<&v_model::Permissions>, _extensions: &v_model::permissions::ArcMap, ) -> v_model::Permissions { @@ -124,20 +130,22 @@ impl Drop for TestDb { } } -// Steps through the process of: +// Steps through the process of // 1. Creating an API user // 2. Retrieve the user -// 3. Update the user's email -// 4. Update the user's permissions -// 5. Create an API token for the user -// 6. Create an API token with excess permissions for the user -// 7. Create an expired API token for the user -// 8. List the active API tokens for the user -// 9. List all API tokens for the user -// 10. Delete the API tokens for the user -// 11. List the deleted API tokens for the user -// 12. Delete the user -// 13. List the deleted user +// 3. Create an API token for the user +// 4. Create an API token with excess permissions for the user +// 5. Create an expired API token for the user +// 6. List the active API tokens for the user +// 7. List all API tokens for the user +// 8. Lookup an API token for the user +// 9. Delete the API tokens for the user +// 10. List the deleted API tokens for the user +// 11. Delete the user +// 12. List the deleted user +// +// Users are never rewritten after they are created, so the user is created with every permission +// the rest of the test relies on. #[tokio::test] async fn test_api_user() { let db = TestDb::new("test_api_user"); @@ -146,41 +154,7 @@ async fn test_api_user() { let api_user_id = TypedUuid::new_v4(); // 1. Create an API user - let api_user = ApiUserStore::::upsert( - &store, - NewApiUser { - id: api_user_id, - permissions: vec![TestPermission::CreateApiKey(api_user_id)].into(), - groups: BTreeSet::new(), - }, - ) - .await - .unwrap(); - - // 2. Retrieve the user - let api_user_lookup = ApiUserStore::get(&store, &api_user.user.id, false) - .await - .unwrap() - .unwrap(); - - assert_eq!(api_user, api_user_lookup); - - // 3. Update the user's email - let api_user = ApiUserStore::::upsert( - &store, - NewApiUser { - id: api_user_id, - permissions: vec![TestPermission::CreateApiKey(api_user_id)].into(), - groups: BTreeSet::new(), - }, - ) - .await - .unwrap(); - - assert_eq!(api_user_id, api_user.user.id); - - // 4. Update the user's permissions - let api_user = ApiUserStore::::upsert( + let api_user = ApiUserStore::::create( &store, NewApiUser { id: api_user_id, @@ -209,7 +183,15 @@ async fn test_api_user() { .can(&TestPermission::DeleteApiKey(api_user_id)) ); - // 5. Create an API token for the user + // 2. Retrieve the user + let api_user_lookup = ApiUserStore::get(&store, &api_user.user.id, false) + .await + .unwrap() + .unwrap(); + + assert_eq!(api_user, api_user_lookup); + + // 3. Create an API token for the user let token = ApiKeyStore::::upsert( &store, NewApiKey { @@ -223,7 +205,7 @@ async fn test_api_user() { .await .unwrap(); - // 6. Create an API token with excess permissions for the user + // 4. Create an API token with excess permissions for the user let excess_token = ApiKeyStore::upsert( &store, NewApiKey { @@ -251,7 +233,7 @@ async fn test_api_user() { .can(&TestPermission::CreateApiUser) ); - // 7. Create an API token with excess permissions for the user + // 5. Create an expired API token for the user let expired_token = ApiKeyStore::::upsert( &store, NewApiKey { @@ -273,7 +255,7 @@ async fn test_api_user() { assert!(expired_token.expires_at < Utc::now()); - // 8. List the active API tokens for the user + // 6. List the active API tokens for the user let tokens = ApiKeyStore::list( &store, ApiKeyFilter { @@ -292,7 +274,7 @@ async fn test_api_user() { assert!(tokens.contains(&token)); assert!(tokens.contains(&excess_token)); - // 9. List all API tokens for the user + // 7. List all API tokens for the user let all_tokens = ApiKeyStore::list( &store, ApiKeyFilter { @@ -310,7 +292,7 @@ async fn test_api_user() { assert!(all_tokens.len() == 3); assert!(all_tokens.contains(&expired_token)); - // 10. Lookup an API token for the user + // 8. Lookup an API token for the user let token_lookup = ApiKeyStore::::get(&store, &token.id, false) .await .unwrap() @@ -318,14 +300,14 @@ async fn test_api_user() { assert_eq!(token.id, token_lookup.id); - // 11. Delete the API tokens for the user + // 9. Delete the API tokens for the user for token in all_tokens { let _ = ApiKeyStore::::delete(&store, &token.id) .await .unwrap(); } - // 12. List the deleted API tokens for the user + // 10. List the deleted API tokens for the user let deleted_tokens = ApiKeyStore::::list( &store, ApiKeyFilter { @@ -347,7 +329,7 @@ async fn test_api_user() { assert!(token.deleted_at.unwrap() < Utc::now()); } - // 13. Delete the user + // 11. Delete the user let api_user = ApiUserStore::::delete(&store, &api_user.user.id) .await .unwrap() @@ -357,7 +339,7 @@ async fn test_api_user() { assert!(api_user.user.deleted_at.unwrap() < Utc::now()); println!("Created api user {:#?}", api_user); - // 14. List the deleted user + // 12. List the deleted user let all_api_users = ApiUserStore::::list( &store, ApiUserFilter { @@ -598,3 +580,536 @@ async fn test_mapper_activation_limit() { assert_eq!(final_mapper.activations, Some(1)); assert!(final_mapper.depleted_at.is_some()); } + +async fn create_user(store: &PostgresStore) -> TypedUuid { + let id = TypedUuid::new_v4(); + ApiUserStore::::create( + store, + NewApiUser { + id, + permissions: Default::default(), + groups: BTreeSet::new(), + }, + ) + .await + .unwrap(); + id +} + +async fn create_client(store: &PostgresStore) -> TypedUuid { + let id = TypedUuid::new_v4(); + OAuthClientStore::upsert(store, NewOAuthClient { id }) + .await + .unwrap(); + id +} + +fn new_key(client_id: TypedUuid, thumbprint: &str) -> NewOAuthClientKey { + NewOAuthClientKey { + id: TypedUuid::new_v4(), + oauth_client_id: client_id, + thumbprint: thumbprint.to_string(), + // A distinct key per thumbprint, which is all these tests need + jwk: PublicJwk::ed25519([*thumbprint.as_bytes().last().unwrap(); 32]), + } +} + +// A service account's permissions are written once with create, then only through a conditional +// update on the generation that was read +#[tokio::test] +async fn test_service_account_permissions() { + let db = TestDb::new("test_service_account_permissions"); + let store = PostgresStore::new(&db.url()).await.unwrap(); + + let client_id = create_client(&store).await; + assert!( + ServiceAccountStore::::get(&store, &client_id) + .await + .unwrap() + .is_none(), + "a client starts without a service account record" + ); + + let account = |permissions: Vec| NewServiceAccount:: { + id: client_id, + permissions: permissions.into(), + }; + + let created = ServiceAccountStore::create(&store, account(vec![TestPermission::CreateApiUser])) + .await + .unwrap(); + assert!(created.permissions.can(&TestPermission::CreateApiUser)); + + // A second create means a concurrent change got there first + let again = ServiceAccountStore::create(&store, account(vec![])).await; + assert!( + matches!(again, Err(StoreError::Conflict)), + "a second create was accepted, got {again:?}" + ); + + // An update from the current generation lands and moves the generation on + let updated = ServiceAccountStore::update(&store, account(vec![]), created.generation) + .await + .unwrap() + .expect("an update from the current generation should land"); + assert!(updated.permissions.is_empty()); + assert_eq!(created.generation + 1, updated.generation); + + // An update from a stale generation is refused and changes nothing + let stale = ServiceAccountStore::update( + &store, + account(vec![TestPermission::CreateApiUser]), + created.generation, + ) + .await + .unwrap(); + assert!(stale.is_none()); + let current = ServiceAccountStore::::get(&store, &client_id) + .await + .unwrap() + .unwrap(); + assert_eq!(updated.permissions, current.permissions); +} + +#[tokio::test] +async fn test_service_account_tokens() { + let db = TestDb::new("test_service_account_tokens"); + let store = PostgresStore::new(&db.url()).await.unwrap(); + + let client_id = create_client(&store).await; + let new_token = || NewServiceAccountToken { + id: TypedUuid::new_v4(), + oauth_client_id: client_id, + expires_at: Utc::now() + TimeDelta::try_seconds(300).unwrap(), + }; + + let token = ServiceAccountTokenStore::create(&store, new_token()) + .await + .unwrap(); + assert_eq!(client_id, token.oauth_client_id); + assert!(token.revoked_at.is_none()); + + // Creating a token never overwrites an existing one + let again = ServiceAccountTokenStore::create( + &store, + NewServiceAccountToken { + id: token.id, + oauth_client_id: client_id, + expires_at: token.expires_at, + }, + ) + .await; + assert!( + matches!(again, Err(StoreError::Conflict)), + "a duplicate token id was accepted, got {again:?}" + ); + + let found = ServiceAccountTokenStore::get(&store, &token.id, false) + .await + .unwrap(); + assert_eq!(Some(token.id), found.map(|token| token.id)); + + // A revoked token is only returned when revoked tokens are asked for + let revoked = ServiceAccountTokenStore::revoke(&store, &token.id) + .await + .unwrap() + .expect("an unrevoked token should be revoked"); + assert!(revoked.revoked_at.is_some()); + assert!( + ServiceAccountTokenStore::get(&store, &token.id, false) + .await + .unwrap() + .is_none() + ); + assert!( + ServiceAccountTokenStore::get(&store, &token.id, true) + .await + .unwrap() + .is_some() + ); + + // Revoking twice finds nothing left to revoke + assert!( + ServiceAccountTokenStore::revoke(&store, &token.id) + .await + .unwrap() + .is_none() + ); + + // Listing only returns live tokens unless revoked or expired ones are asked for + let expired = ServiceAccountTokenStore::create( + &store, + NewServiceAccountToken { + id: TypedUuid::new_v4(), + oauth_client_id: client_id, + expires_at: Utc::now() - TimeDelta::try_seconds(60).unwrap(), + }, + ) + .await + .unwrap(); + let live = ServiceAccountTokenStore::create(&store, new_token()) + .await + .unwrap(); + let other_client = create_client(&store).await; + ServiceAccountTokenStore::create( + &store, + NewServiceAccountToken { + id: TypedUuid::new_v4(), + oauth_client_id: other_client, + expires_at: Utc::now() + TimeDelta::try_seconds(300).unwrap(), + }, + ) + .await + .unwrap(); + + let list = |revoked: bool, expired: bool| { + let store = &store; + async move { + ServiceAccountTokenStore::list( + store, + ServiceAccountTokenFilter { + oauth_client_id: Some(vec![client_id]), + revoked, + expired, + }, + &ListPagination::default(), + ) + .await + .unwrap() + .into_iter() + .map(|token| token.id) + .collect::>() + } + }; + assert_eq!(vec![live.id], list(false, false).await); + let everything = list(true, true).await; + assert_eq!(3, everything.len()); + assert!(everything.contains(&token.id) && everything.contains(&expired.id)); + + // Revoking one token leaves the client's other tokens alone + let other = ServiceAccountTokenStore::create(&store, new_token()) + .await + .unwrap(); + assert!( + ServiceAccountTokenStore::get(&store, &other.id, false) + .await + .unwrap() + .is_some() + ); +} + +#[tokio::test] +async fn test_oauth_client_keys() { + let db = TestDb::new("test_oauth_client_keys"); + let store = PostgresStore::new(&db.url()).await.unwrap(); + + let client_id = create_client(&store).await; + let first = OAuthClientKeyStore::insert(&store, new_key(client_id, "thumbprint-a")) + .await + .unwrap(); + + // The key reads back from its JSONB column exactly as it was written + assert_eq!(new_key(client_id, "thumbprint-a").jwk, first.jwk); + let second = OAuthClientKeyStore::insert(&store, new_key(client_id, "thumbprint-b")) + .await + .unwrap(); + + // The client carries its keys + let client = OAuthClientStore::get(&store, &client_id, false) + .await + .unwrap() + .unwrap(); + let thumbprints = client + .keys + .iter() + .map(|key| key.thumbprint.as_str()) + .collect::>(); + assert_eq!( + BTreeSet::from(["thumbprint-a", "thumbprint-b"]), + thumbprints + ); + + // Keys can be found by thumbprint, which is how an assertion's kid is resolved + let found = OAuthClientKeyStore::list( + &store, + OAuthClientKeyFilter { + thumbprint: Some(vec!["thumbprint-b".to_string()]), + ..Default::default() + }, + &ListPagination::default(), + ) + .await + .unwrap(); + assert_eq!( + vec![second.id], + found.iter().map(|key| key.id).collect::>() + ); + + // A deleted key leaves listings and its client, but is still retrievable when asked for + let deleted = OAuthClientKeyStore::delete(&store, &first.id) + .await + .unwrap() + .unwrap(); + assert!(deleted.deleted_at.is_some()); + assert!( + OAuthClientKeyStore::get(&store, &first.id, false) + .await + .unwrap() + .is_none() + ); + let client = OAuthClientStore::get(&store, &client_id, false) + .await + .unwrap() + .unwrap(); + assert_eq!( + vec![second.id], + client.keys.iter().map(|key| key.id).collect::>() + ); + + // Deleting again keeps the original deletion time + let deleted_again = OAuthClientKeyStore::delete(&store, &first.id) + .await + .unwrap() + .unwrap(); + assert_eq!(deleted.deleted_at, deleted_again.deleted_at); + + // A thumbprint is unique across every client, including keys that have been deleted + let other_client = create_client(&store).await; + for thumbprint in ["thumbprint-a", "thumbprint-b"] { + let result = OAuthClientKeyStore::insert(&store, new_key(other_client, thumbprint)).await; + assert!( + matches!(result, Err(StoreError::Conflict)), + "{thumbprint} was registered twice, got {result:?}" + ); + } +} + +// An assertion is accepted once per client, and expired assertions can be pruned +#[tokio::test] +async fn test_oauth_client_assertions() { + let db = TestDb::new("test_oauth_client_assertions"); + let store = PostgresStore::new(&db.url()).await.unwrap(); + + let client_id = create_client(&store).await; + let other_client = create_client(&store).await; + let expires_at = Utc::now() + TimeDelta::minutes(5); + + let assertion = + |client: TypedUuid, jti: &str, expires_at| NewOAuthClientAssertion { + oauth_client_id: client, + jti: jti.to_string(), + expires_at, + }; + + OAuthClientAssertionStore::record(&store, assertion(client_id, "jti-1", expires_at)) + .await + .unwrap(); + + // Presenting the same jti again is a replay + let replay = + OAuthClientAssertionStore::record(&store, assertion(client_id, "jti-1", expires_at)).await; + assert!( + matches!(replay, Err(StoreError::Conflict)), + "a replayed assertion was accepted, got {replay:?}" + ); + + // The jti is chosen by the client, so another client may use the same value + OAuthClientAssertionStore::record(&store, assertion(other_client, "jti-1", expires_at)) + .await + .unwrap(); + + // Only assertions that expired before the cutoff are pruned + let expired = Utc::now() - TimeDelta::minutes(10); + OAuthClientAssertionStore::record(&store, assertion(client_id, "jti-2", expired)) + .await + .unwrap(); + let pruned = OAuthClientAssertionStore::delete_expired(&store, Utc::now()) + .await + .unwrap(); + assert_eq!(1, pruned); + + // A pruned assertion's jti no longer conflicts, while live ones still do + OAuthClientAssertionStore::record(&store, assertion(client_id, "jti-2", expires_at)) + .await + .unwrap(); + let replay = + OAuthClientAssertionStore::record(&store, assertion(client_id, "jti-1", expires_at)).await; + assert!(matches!(replay, Err(StoreError::Conflict))); +} + +// A conditional write lands only when the record is unchanged since it was read, which is what +// keeps concurrent permission changes from overwriting each other +#[tokio::test] +async fn test_conditional_updates() { + let db = TestDb::new("test_conditional_updates"); + let store = PostgresStore::new(&db.url()).await.unwrap(); + + let user_id = create_user(&store).await; + let read = ApiUserStore::::get(&store, &user_id, false) + .await + .unwrap() + .unwrap(); + + let change = |permissions: Vec| NewApiUser { + id: user_id, + permissions: permissions.into(), + groups: BTreeSet::new(), + }; + + // The first write from this read lands + let written = ApiUserStore::update( + &store, + change(vec![TestPermission::CreateApiUser]), + read.user.generation, + ) + .await + .unwrap() + .expect("a write from a current read should land"); + assert_eq!(read.user.generation + 1, written.user.generation); + + // A second write from the same, now stale, read is rejected and changes nothing + let stale = ApiUserStore::update( + &store, + change(vec![TestPermission::GetApiKey(user_id)]), + read.user.generation, + ) + .await + .unwrap(); + assert!(stale.is_none()); + let current = ApiUserStore::::get(&store, &user_id, false) + .await + .unwrap() + .unwrap(); + assert_eq!(written.user.permissions, current.user.permissions); + + // A deleted user is never written + ApiUserStore::::delete(&store, &user_id) + .await + .unwrap(); + let deleted = ApiUserStore::update(&store, change(vec![]), current.user.generation) + .await + .unwrap(); + assert!(deleted.is_none()); + + // Groups follow the same rule + let group_id = TypedUuid::new_v4(); + let group = AccessGroupStore::::upsert( + &store, + &NewAccessGroup { + id: group_id, + name: "engineering".to_string(), + permissions: Default::default(), + }, + ) + .await + .unwrap(); + let change = |name: &str, permissions: Vec| NewAccessGroup:: { + id: group_id, + name: name.to_string(), + permissions: permissions.into(), + }; + + // A write from the current read lands, and changes the permissions but never the name, even + // when a different name is supplied. Mappers resolve groups by name. + let written = AccessGroupStore::update( + &store, + &change("platform", vec![TestPermission::CreateApiUser]), + group.generation, + ) + .await + .unwrap() + .expect("a write from a current read should land"); + assert_eq!("engineering", written.name); + assert_eq!( + v_model::Permissions::from(vec![TestPermission::CreateApiUser]), + written.permissions + ); + assert_eq!(group.generation + 1, written.generation); + + // Upserting an existing group keeps its name too + let upserted = AccessGroupStore::upsert( + &store, + &change("other", vec![TestPermission::CreateApiUser]), + ) + .await + .unwrap(); + assert_eq!("engineering", upserted.name); + + let stale = AccessGroupStore::update(&store, &change("engineering", vec![]), group.generation) + .await + .unwrap(); + assert!(stale.is_none()); +} + +// Inserting a user never changes one that already exists, which is what lets a service user be +// created again without resetting its permissions +#[tokio::test] +async fn test_insert_never_overwrites_a_user() { + let db = TestDb::new("test_insert_never_overwrites_a_user"); + let store = PostgresStore::new(&db.url()).await.unwrap(); + + let user_id = TypedUuid::new_v4(); + let user = |permissions: Vec| NewApiUser { + id: user_id, + permissions: permissions.into(), + groups: BTreeSet::new(), + }; + + let created = ApiUserStore::create(&store, user(vec![TestPermission::CreateApiUser])) + .await + .unwrap(); + assert!(created.user.permissions.can(&TestPermission::CreateApiUser)); + + let again = ApiUserStore::create(&store, user(vec![])).await; + assert!( + matches!(again, Err(StoreError::Conflict)), + "a second insert was accepted, got {again:?}" + ); + + let current = ApiUserStore::::get(&store, &user_id, false) + .await + .unwrap() + .unwrap(); + assert_eq!(created.user.permissions, current.user.permissions); + assert_eq!(created.user.generation, current.user.generation); +} + +/// A failed login attempt keeps the error it failed with, so the client it redirects to is told +/// why the login did not complete +#[tokio::test] +async fn test_login_attempt_error_round_trips() { + let db = TestDb::new("test_login_attempt_error_round_trips"); + let store = PostgresStore::new(&db.url()).await.unwrap(); + + let client_id = create_client(&store).await; + let attempt = NewLoginAttempt::new( + "google".to_string(), + client_id, + Some("https://example.com/callback".to_string()), + String::new(), + "authorization_code".to_string(), + ) + .unwrap(); + let attempt = LoginAttemptStore::upsert(&store, attempt).await.unwrap(); + assert_eq!(None, attempt.error); + + let mut update: NewLoginAttempt = attempt.into(); + update.attempt_state = LoginAttemptState::Failed; + update.error = Some("access_denied".to_string()); + update.provider_error = Some("access_denied".to_string()); + let failed = LoginAttemptStore::update_if_state(&store, update, LoginAttemptState::New) + .await + .unwrap(); + assert_eq!(Some("access_denied"), failed.error.as_deref()); + + let read = LoginAttemptStore::get(&store, &failed.id) + .await + .unwrap() + .unwrap(); + assert_eq!(Some("access_denied"), read.error.as_deref()); + assert_eq!(Some("access_denied"), read.provider_error.as_deref()); + assert_eq!( + Some("https://example.com/callback?error=access_denied".to_string()), + read.callback_url().unwrap() + ); +}