-
Notifications
You must be signed in to change notification settings - Fork 6
feat(sts): exchange opaque API keys at /.sts by hash lookup #235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| //! API keys (ADR-013): opaque secrets a service account presents at `/.sts` | ||
| //! in place of an OIDC token. Nothing here verifies a signature — there is | ||
| //! none. The key's standing lives in source.coop, keyed by the key's SHA-256, | ||
| //! and this module is the wasm-free half of the exchange: recognising a key, | ||
| //! hashing it, and sealing credentials for the account the API names. | ||
|
|
||
| use multistore::error::ProxyError; | ||
| use multistore::types::{RoleConfig, TemporaryCredentials}; | ||
| use multistore_sts::sts::mint_temporary_credentials; | ||
| use multistore_sts::TokenKey; | ||
| use serde::Deserialize; | ||
| use sha2::{Digest, Sha256}; | ||
|
|
||
| /// Every key starts with this, followed by 30 random base62 characters and | ||
| /// the six-character checksum of those 30: a fixed 40 characters, the pattern | ||
| /// secret scanners are given. | ||
| pub const API_KEY_PREFIX: &str = "sck_"; | ||
| const API_KEY_LEN: usize = 40; | ||
| const BASE62: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; | ||
|
|
||
| /// The token, trimmed, if it has exactly a key's shape and its checksum | ||
| /// holds; `None` for anything else — a JWT, a truncated or mistyped key, the | ||
| /// wrong case — so the JWT path or a local refusal takes it without a lookup. | ||
| /// Whitespace is trimmed first because every hand-made token file ends in a | ||
| /// newline, and some SDKs send it. | ||
| pub fn parse_api_key(token: &str) -> Option<&str> { | ||
| let key = token.trim(); | ||
| let rest = key.strip_prefix(API_KEY_PREFIX)?; | ||
| (key.len() == API_KEY_LEN | ||
| && rest.bytes().all(|b| b.is_ascii_alphanumeric()) | ||
| && rest.as_bytes()[30..] == checksum(&rest.as_bytes()[..30])) | ||
| .then_some(key) | ||
| } | ||
|
|
||
| /// A key's last six characters: the CRC-32 of the thirty before them (IEEE, | ||
| /// as zlib computes it), in base62, most significant digit first. | ||
| fn checksum(body: &[u8]) -> [u8; 6] { | ||
| let mut crc = !0u32; | ||
| for &b in body { | ||
| crc ^= u32::from(b); | ||
| for _ in 0..8 { | ||
| crc = if crc & 1 == 1 { | ||
| (crc >> 1) ^ 0xEDB8_8320 | ||
| } else { | ||
| crc >> 1 | ||
| }; | ||
| } | ||
| } | ||
| let mut n = !crc; | ||
| let mut digits = [b'0'; 6]; | ||
| for digit in digits.iter_mut().rev() { | ||
| *digit = BASE62[(n % 62) as usize]; | ||
| n /= 62; | ||
| } | ||
| digits | ||
| } | ||
|
|
||
| /// Whether the token so much as looks like a key — the prefix alone. Used to | ||
| /// refuse a key sent where it would be logged, before checking anything else. | ||
| pub fn looks_like_api_key(token: &str) -> bool { | ||
| token.trim_start().starts_with(API_KEY_PREFIX) | ||
| } | ||
|
|
||
| /// Hex SHA-256 of a key: the record's key in source.coop, and all the proxy | ||
| /// ever sends of it. | ||
| pub fn key_hash(key: &str) -> String { | ||
| Sha256::digest(key.as_bytes()) | ||
| .iter() | ||
| .map(|b| format!("{b:02x}")) | ||
| .collect() | ||
| } | ||
|
|
||
| /// The Source API's answer for a presented key | ||
| /// (`POST /api/v1/service-account-keys/exchanges`): whether it may be | ||
| /// exchanged and, if so, for whom. Unknown, revoked, expired and disabled all | ||
| /// come back inactive and unnamed, so nothing distinguishes them here. | ||
| #[derive(Debug, Clone, Deserialize)] | ||
| pub struct KeyStanding { | ||
| pub active: bool, | ||
| #[serde(default)] | ||
| pub account_id: Option<String>, | ||
| #[serde(default)] | ||
| pub key_id: Option<String>, | ||
| } | ||
|
|
||
| /// Credentials for an account the API has vouched for, sealed the way the | ||
| /// STS route seals every session, for the duration the client asked for | ||
| /// within the role's cap. The floor and default are AWS's and multistore's. | ||
| pub fn credentials_for( | ||
| role: &RoleConfig, | ||
| account_id: &str, | ||
| duration_seconds: Option<u64>, | ||
| token_key: &TokenKey, | ||
| ) -> Result<TemporaryCredentials, ProxyError> { | ||
| let duration = duration_seconds | ||
| .unwrap_or(3600) | ||
| .clamp(900, role.max_session_duration_secs); | ||
| let mut creds = mint_temporary_credentials( | ||
| role, | ||
| account_id, | ||
| duration, | ||
| "STSPRXY", | ||
| &serde_json::json!({}), | ||
| ); | ||
| creds.session_token = token_key.seal(&creds)?; | ||
| Ok(creds) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.