| 1 | use super::*; |
| 2 | use std::sync::Mutex; |
| 3 | |
| 4 | pub(super) type MockForm = Vec<(String, String)>; |
| 5 | pub(super) type MockPost = (String, MockForm); |
| 6 | pub(super) struct SiwcSigningFixture { |
| 7 | pair: ring::signature::Ed25519KeyPair, |
| 8 | pub(super) keys: ChatgptKeys, |
| 9 | } |
| 10 | |
| 11 | impl SiwcSigningFixture { |
| 12 | pub(super) fn new() -> Self { |
| 13 | use ring::signature::KeyPair as _; |
| 14 | let pkcs8 = |
| 15 | ring::signature::Ed25519KeyPair::generate_pkcs8(&ring::rand::SystemRandom::new()) |
| 16 | .unwrap(); |
| 17 | let pair = ring::signature::Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap(); |
| 18 | let keys: JwkSet = serde_json::from_value(serde_json::json!({"keys": [{ |
| 19 | "kty": "OKP", "crv": "Ed25519", "kid": "siwc-fixture", "alg": "EdDSA", "use": "sig", |
| 20 | "x": URL_SAFE_NO_PAD.encode(pair.public_key().as_ref()) |
| 21 | }]})) |
| 22 | .unwrap(); |
| 23 | Self { |
| 24 | pair, |
| 25 | keys: keys.into(), |
| 26 | } |
| 27 | } |
| 28 | pub(super) fn token(&self, claims: Value) -> String { |
| 29 | let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"EdDSA","kid":"siwc-fixture"}"#); |
| 30 | let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap()); |
| 31 | let message = format!("{header}.{payload}"); |
| 32 | format!( |
| 33 | "{message}.{}", |
| 34 | URL_SAFE_NO_PAD.encode(self.pair.sign(message.as_bytes()).as_ref()) |
| 35 | ) |
| 36 | } |
| 37 | #[cfg(test)] |
| 38 | pub(super) fn id_claims(&self) -> Value { |
| 39 | serde_json::json!({"iss": CHATGPT_OAUTH_ISSUER, "aud": "oaiapp_codewhale_test", "sub": "test-sub", "nonce": "pending-nonce", "exp": now_unix_secs().unwrap() + 3600}) |
| 40 | } |
| 41 | pub(super) fn access(&self, subject: &str) -> String { |
| 42 | self.token(serde_json::json!({"iss": CHATGPT_OAUTH_ISSUER, "aud": CHATGPT_OAUTH_RESOURCE, "sub": subject, "client_id": "oaiapp_codewhale_test", "scope": CHATGPT_OAUTH_SCOPE, "exp": now_unix_secs().unwrap() + 3600})) |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | struct SiwcRefreshClient { |
| 47 | pub(super) keys: ChatgptKeys, |
| 48 | access: String, |
| 49 | posts: Mutex<Vec<MockPost>>, |
| 50 | } |
| 51 | impl OAuthFormClient for SiwcRefreshClient { |
| 52 | fn post_form(&self, url: &str, form: &[(&str, &str)]) -> Result<(u16, String)> { |
| 53 | self.posts.lock().unwrap().push(( |
| 54 | url.to_string(), |
| 55 | form.iter() |
| 56 | .map(|(k, v)| (k.to_string(), v.to_string())) |
| 57 | .collect(), |
| 58 | )); |
| 59 | Ok((200, serde_json::json!({"access_token": self.access, "refresh_token": "rotated-refresh", "expires_in": 3600, "scope": CHATGPT_OAUTH_SCOPE, "token_type": "Bearer"}).to_string())) |
| 60 | } |
| 61 | fn chatgpt_jwks(&self, _: &str) -> Result<ChatgptKeys> { |
| 62 | Ok(self.keys.clone()) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | pub fn siwc_refresh_rotates_atomically_and_rejects_a_different_account< |
| 67 | T: PartialEq + std::fmt::Debug, |
| 68 | >( |
| 69 | scope_of: impl Fn(&Config) -> T, |
| 70 | ) { |
| 71 | let _lock = crate::test_support::lock_test_env(); |
| 72 | let home = tempfile::tempdir().unwrap(); |
| 73 | let root = home.path().canonicalize().unwrap(); |
| 74 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root); |
| 75 | let signer = SiwcSigningFixture::new(); |
| 76 | let mut config = Config::default(); |
| 77 | config.provider = Some("openai-codex".into()); |
| 78 | install_test_chatgpt_registration(&mut config).unwrap(); |
| 79 | let original = get_owned_credentials_read_only(OAuthProvider::Chatgpt, &config).unwrap(); |
| 80 | let original_scope = scope_of(&config); |
| 81 | let path = configured_owned_auth_file_path(OAuthProvider::Chatgpt, &config) |
| 82 | .unwrap() |
| 83 | .unwrap(); |
| 84 | let name = path.file_name().unwrap().to_str().unwrap(); |
| 85 | codewhale_config::with_xai_oauth_lifecycle_lock(|store| { |
| 86 | let mut file = load_owned_auth_file_from_store(store, name)?.unwrap(); |
| 87 | for entry in file.values_mut() { |
| 88 | entry.expires_at = Some("2000-01-01T00:00:00Z".to_string()); |
| 89 | } |
| 90 | write_auth_file_to_store(store, name, &file, true) |
| 91 | }) |
| 92 | .unwrap(); |
| 93 | let before = std::fs::read(&path).unwrap(); |
| 94 | let wrong = SiwcRefreshClient { |
| 95 | keys: signer.keys.clone(), |
| 96 | access: signer.access("another-account"), |
| 97 | posts: Mutex::new(Vec::new()), |
| 98 | }; |
| 99 | assert!(get_owned_credentials_with(OAuthProvider::Chatgpt, &config, &wrong).is_err()); |
| 100 | assert_eq!(std::fs::read(&path).unwrap(), before); |
| 101 | let right = SiwcRefreshClient { |
| 102 | keys: signer.keys.clone(), |
| 103 | access: signer.access("test-sub"), |
| 104 | posts: Mutex::new(Vec::new()), |
| 105 | }; |
| 106 | let refreshed = get_owned_credentials_with(OAuthProvider::Chatgpt, &config, &right).unwrap(); |
| 107 | assert_ne!(original.access_token, refreshed.access_token); |
| 108 | assert_eq!(original_scope, scope_of(&config)); |
| 109 | assert_eq!(refreshed.refresh_token.as_deref(), Some("rotated-refresh")); |
| 110 | assert_eq!( |
| 111 | official_chatgpt_registration(&config).unwrap().subject, |
| 112 | "test-sub" |
| 113 | ); |
| 114 | assert!(get_owned_credentials_read_only(OAuthProvider::Chatgpt, &config).is_ok()); |
| 115 | let posts = right.posts.lock().unwrap(); |
| 116 | assert_eq!( |
| 117 | posts[0].0, |
| 118 | "https://auth.openai.com/api/accounts/oauth/token" |
| 119 | ); |
| 120 | assert!( |
| 121 | posts[0] |
| 122 | .1 |
| 123 | .contains(&("client_id".to_string(), "oaiapp_codewhale_test".to_string())) |
| 124 | ); |
| 125 | assert!( |
| 126 | posts[0] |
| 127 | .1 |
| 128 | .contains(&("resource".to_string(), CHATGPT_OAUTH_RESOURCE.to_string())) |
| 129 | ); |
| 130 | assert!( |
| 131 | posts[0] |
| 132 | .1 |
| 133 | .contains(&("refresh_token".to_string(), "siwc-test-refresh".to_string())) |
| 134 | ); |
| 135 | } |
| 136 | |
| 137 | pub fn descriptor() -> PluginOAuthConfig { |
| 138 | PluginOAuthConfig { |
| 139 | issuer: "https://issuer.example".into(), |
| 140 | authorization_endpoint: "https://issuer.example/authorize".into(), |
| 141 | token_endpoint: "https://issuer.example/token".into(), |
| 142 | client_id: "public-client".into(), |
| 143 | scopes: vec!["models:invoke".into()], |
| 144 | resource: Some("https://api.example/oauth".into()), |
| 145 | callback_path: plugin_callback_path(), |
| 146 | } |
| 147 | } |
| 148 |