sigstore 0.14.0

An experimental crate to interact with sigstore
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//
// Copyright 2022 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! This provides a method for retreiving a OpenID Connect ID Token and scope from the sigstore project.
//!
//! The main entry points are:
//! - [`OpenIDAuthorize::auth_url`](OpenIDAuthorize::auth_url) (synchronous)
//! - [`OpenIDAuthorize::auth_url_async`](OpenIDAuthorize::auth_url_async) (async)
//!
//! Both require four parameters:
//! - `client_id`: the client ID of the application
//! - `client_secret`: the client secret of the application
//! - `issuer`: the URL of the OpenID Connect server
//! - `redirect_uri`: the URL of the callback endpoint
//!
//! They return the following:
//!
//! - `authorize_url` is a URL that can be opened in a browser. The user will be
//!   prompted to login and authorize the application. The user will be redirected to
//!   the `redirect_uri` URL with a code parameter.
//!
//! - `client` is a client object that can be used to make requests to the OpenID
//!   Connect server.
//!
//! - `nonce` is a random value that is used to prevent replay attacks.
//!
//! - `pkce_verifier` is a PKCE verifier that can be used to generate the code_verifier
//!   value.
//!
//! Once you have recieved the above tuple, you can use:
//! - [`RedirectListener::redirect_listener`](RedirectListener::redirect_listener) (synchronous)
//! - [`RedirectListener::redirect_listener_async`](RedirectListener::redirect_listener_async) (async)
//!
//! to get the ID Token and scope.
//!
//! The `IdTokenClaims` this contains params such as `email` and the `access_token`.
//!
//! It maybe prefered to instead develop your own listener. If so bypass using the
//! [`RedirectListener::redirect_listener`](RedirectListener::redirect_listener) /
//! [`RedirectListener::redirect_listener_async`](RedirectListener::redirect_listener_async) function and
//! simply send the values retrieved from the [`OpenIDAuthorize::auth_url`](OpenIDAuthorize::auth_url) /
//! [`OpenIDAuthorize::auth_url_async`](OpenIDAuthorize::auth_url_async)
//! to your own listener.
//!
//!
//! **Warning:** [`OpenIDAuthorize::auth_url`](OpenIDAuthorize::auth_url) performs
//! blocking operations. Because of that it can cause panics at runtime if invoked inside of `async` code.
//! If you need to use this function inside of an async code you must wrap it inside of a `spawn_blocking` instruction:
//!
//! ```rust,ignore
//! use tokio::task::spawn_blocking;
//!
//! async fn my_async_function() {
//!    // ... your code
//!
//!    let oidc_url = spawn_blocking(||
//!     oauth::openidflow::OpenIDAuthorize::new(
//!       "sigstore",
//!       "",
//!       "https://oauth2.sigstore.dev/auth",
//!       "http://localhost:8080",
//!     )
//!     .auth_url()
//!    )
//!    .await
//!    .expect("Error spawning blocking task");
//!
//!    // ... your code
//! }
//! ```
//! This of course has a performance hit when used inside of an async function.

use std::{
    io::{BufRead, BufReader, Write},
    net::TcpListener,
};

use openidconnect::{
    AuthorizationCode, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce, PkceCodeChallenge,
    PkceCodeVerifier, RedirectUrl, Scope,
    core::{
        CoreAuthenticationFlow, CoreClient, CoreIdToken, CoreIdTokenClaims, CoreIdTokenVerifier,
        CoreProviderMetadata, CoreTokenResponse,
    },
};
use tracing::error;
use url::Url;

use crate::errors::{Result, SigstoreError};
use crate::oauth::http_client::AsyncReqwestClient;
use crate::oauth::http_client::SyncReqwestClient;

pub(crate) type OpenIdClient = openidconnect::core::CoreClient<
    openidconnect::EndpointSet,      // HasAuthUrl
    openidconnect::EndpointNotSet,   // HasDeviceAuthUrl
    openidconnect::EndpointNotSet,   // HasIntrospectionUrl
    openidconnect::EndpointNotSet,   // HasRevocationUrl
    openidconnect::EndpointMaybeSet, // HasTokenUrl
    openidconnect::EndpointMaybeSet, // HasUserInfoUrl
>;

#[derive(Debug)]
pub struct OpenIDAuthorize {
    oidc_cliend_id: String,
    oidc_client_secret: String,
    oidc_issuer: String,
    redirect_url: String,
}

impl OpenIDAuthorize {
    //! Create a new OpenIDAuthorize struct
    //!
    //! # Arguments
    //!
    //! * `client_id` - the client ID of the application
    //! * `client_secret` - the client secret of the application
    //! * `issuer` - the URL of the OpenID Connect server
    //! * `redirect_url` - client redirect URL
    //! # Example
    //!
    //! ```rust,ignore
    //! use sigstore::oauth::openidflow::OpenIDAuthorize;
    //!
    //! let oidc = OpenIDAuthorize::new("client_id", "client_secret", "https://example.com", "http://localhost:8080").auth_url();
    //! ```
    pub fn new(client_id: &str, client_secret: &str, issuer: &str, redirect_url: &str) -> Self {
        Self {
            oidc_cliend_id: client_id.to_string(),
            oidc_client_secret: client_secret.to_string(),
            oidc_issuer: issuer.to_string(),
            redirect_url: redirect_url.to_string(),
        }
    }

    fn auth_url_internal(
        &self,
        provider_metadata: CoreProviderMetadata,
    ) -> Result<(Url, OpenIdClient, Nonce, PkceCodeVerifier)> {
        let client_id = ClientId::new(self.oidc_cliend_id.to_owned());
        let client_secret = ClientSecret::new(self.oidc_client_secret.to_owned());

        let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();

        let client =
            CoreClient::from_provider_metadata(provider_metadata, client_id, Some(client_secret))
                .set_redirect_uri(
                    RedirectUrl::new(self.redirect_url.to_owned()).expect("Invalid redirect URL"),
                );

        let (authorize_url, _, nonce) = client
            .authorize_url(
                CoreAuthenticationFlow::AuthorizationCode,
                CsrfToken::new_random,
                Nonce::new_random,
            )
            .add_scope(Scope::new("email".to_string()))
            .set_pkce_challenge(pkce_challenge)
            .url();
        Ok((authorize_url, client, nonce, pkce_verifier))
    }

    pub fn auth_url(&self) -> Result<(Url, OpenIdClient, Nonce, PkceCodeVerifier)> {
        let http_client = SyncReqwestClient(
            reqwest::blocking::ClientBuilder::new()
                // Following redirects opens the client up to SSRF vulnerabilities.
                .redirect(reqwest::redirect::Policy::none())
                .build()?,
        );

        let issuer = IssuerUrl::new(self.oidc_issuer.to_owned()).expect("Missing the OIDC_ISSUER.");

        let provider_metadata =
            CoreProviderMetadata::discover(&issuer, &http_client).map_err(|err| {
                error!("Error is: {:?}", err);
                SigstoreError::ClaimsVerificationError
            })?;

        self.auth_url_internal(provider_metadata)
    }

    pub async fn auth_url_async(&self) -> Result<(Url, OpenIdClient, Nonce, PkceCodeVerifier)> {
        let async_http_client = AsyncReqwestClient(
            reqwest::ClientBuilder::new()
                // Following redirects opens the client up to SSRF vulnerabilities.
                .redirect(reqwest::redirect::Policy::none())
                .build()?,
        );

        let issuer = IssuerUrl::new(self.oidc_issuer.to_owned()).expect("Missing the OIDC_ISSUER.");

        let provider_metadata = CoreProviderMetadata::discover_async(issuer, &async_http_client)
            .await
            .map_err(|err| {
                error!("Error is: {:?}", err);
                SigstoreError::ClaimsVerificationError
            })?;

        self.auth_url_internal(provider_metadata)
    }
}

pub struct RedirectListener {
    client_redirect_host: String,
    client: OpenIdClient,
    nonce: Nonce,
    pkce_verifier: PkceCodeVerifier,
}

impl RedirectListener {
    //! Create a new RedirectListener struct
    //!
    //! # Arguments
    //!
    //! * `client_redirect_host` - The client callback host IP:PORT
    //! * `client` - CoreClient instance (returned from OpenIDAuthorize)
    //! * `nonce` - Nonce (returned from OpenIDAuthorize)
    //! * `pkce_verifier` - client redirect URL
    //! # Example
    //!
    //! ```rust,ignore
    //! use sigstore::oauth::openidflow::RedirectListener;
    //!
    //! let oidc = RedirectListener::new("127.0.0.1:8080", client, nonce, pkce_verifier).redirect_listener_async().await;
    //! ```
    pub fn new(
        client_redirect_host: &str,
        client: OpenIdClient,
        nonce: Nonce,
        pkce_verifier: PkceCodeVerifier,
    ) -> Self {
        Self {
            client_redirect_host: client_redirect_host.to_string(),
            client,
            nonce,
            pkce_verifier,
        }
    }

    fn redirect_listener_internal(&self) -> Result<AuthorizationCode> {
        let listener = TcpListener::bind(self.client_redirect_host.clone())?;
        #[allow(clippy::manual_flatten)]
        for stream in listener.incoming() {
            if let Ok(mut stream) = stream {
                let code;
                {
                    let mut reader = BufReader::new(&stream);

                    let mut request_line = String::new();
                    reader.read_line(&mut request_line)?;

                    let client_redirect_host = request_line
                        .split_whitespace()
                        .nth(1)
                        .ok_or(SigstoreError::RedirectUrlRequestLineError)?;
                    let url =
                        Url::parse(format!("http://localhost{client_redirect_host}").as_str())?;

                    let code_pair = url
                        .query_pairs()
                        .find(|pair| {
                            let (key, _) = pair;
                            key == "code"
                        })
                        .ok_or(SigstoreError::CodePairError)?;

                    let (_, value) = code_pair;
                    code = AuthorizationCode::new(value.into_owned());
                }

                let html_page = r#"<html>
                <title>Sigstore Auth</title>
                <body>
                <h1>Sigstore Auth Successful</h1>
                <p>You may now close this page.</p>
                </body>
                </html>"#;
                let response = format!(
                    "HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
                    html_page.len(),
                    html_page
                );
                stream.write_all(response.as_bytes())?;

                return Ok(code);
            }
        }
        Err(SigstoreError::CodePairError)
    }

    pub fn redirect_listener(self) -> Result<(CoreIdTokenClaims, CoreIdToken)> {
        let http_client = SyncReqwestClient(
            reqwest::blocking::ClientBuilder::new()
                // Following redirects opens the client up to SSRF vulnerabilities.
                .redirect(reqwest::redirect::Policy::none())
                .build()?,
        );

        let code = self.redirect_listener_internal()?;

        let token_response = self
            .client
            .exchange_code(code)?
            .set_pkce_verifier(self.pkce_verifier)
            .request(&http_client)
            .map_err(|_| SigstoreError::ClaimsAccessPointError)?;

        Self::extract_token_and_claims(
            &token_response,
            &self.client.id_token_verifier(),
            self.nonce,
        )
    }

    pub async fn redirect_listener_async(self) -> Result<(CoreIdTokenClaims, CoreIdToken)> {
        let async_http_client = AsyncReqwestClient(
            reqwest::ClientBuilder::new()
                // Following redirects opens the client up to SSRF vulnerabilities.
                .redirect(reqwest::redirect::Policy::none())
                .build()?,
        );

        let code = self.redirect_listener_internal()?;

        let token_response = self
            .client
            .exchange_code(code)?
            .set_pkce_verifier(self.pkce_verifier)
            .request_async(&async_http_client)
            .await
            .map_err(|_| SigstoreError::ClaimsAccessPointError)?;

        Self::extract_token_and_claims(
            &token_response,
            &self.client.id_token_verifier(),
            self.nonce,
        )
    }

    fn extract_token_and_claims(
        token_response: &CoreTokenResponse,
        id_token_verifier: &CoreIdTokenVerifier,
        nonce: Nonce,
    ) -> Result<(CoreIdTokenClaims, CoreIdToken)> {
        let id_token = token_response
            .extra_fields()
            .id_token()
            .ok_or(SigstoreError::NoIDToken)?;

        let id_token_claims: &CoreIdTokenClaims = token_response
            .extra_fields()
            .id_token()
            .expect("Server did not return an ID token")
            .claims(id_token_verifier, &nonce)
            .map_err(|_| SigstoreError::ClaimsVerificationError)?;
        Ok((id_token_claims.clone(), id_token.clone()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_auth_url(url: &str) {
        assert!(url.contains("https://oauth2.sigstore.dev/auth"));
        assert!(url.contains("response_type=code"));
        assert!(url.contains("client_id=sigstore"));
        assert!(url.contains("scope=openid+email"));
    }

    #[test]
    fn test_auth_url() {
        let oidc_url = OpenIDAuthorize::new(
            "sigstore",
            "some_secret",
            "https://oauth2.sigstore.dev/auth",
            "http://localhost:8080",
        )
        .auth_url()
        .unwrap();
        assert_auth_url(oidc_url.0.to_string().as_str());
    }

    #[tokio::test]
    async fn test_auth_url_async() {
        let oidc_url = OpenIDAuthorize::new(
            "sigstore",
            "some_secret",
            "https://oauth2.sigstore.dev/auth",
            "http://localhost:8080",
        )
        .auth_url_async()
        .await
        .unwrap();
        assert_auth_url(oidc_url.0.to_string().as_str());
    }
}