Skip to content

Add unsafe-no-cors mode #1533

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

Closed
wants to merge 0 commits into from

Conversation

bvandersloot-mozilla
Copy link
Contributor

@bvandersloot-mozilla bvandersloot-mozilla commented Nov 7, 2022

We identified a potential need for a more sustainable no-cors mode in discussion surrounding FedCM. The purpose is to create a browser-process priveleged mode that will not fail the Access-Control-Allow-Origin CORS checks while otherwise behaving like a normal CORS request.

Here are the deviations I have made from cors mode to make unsafe-no-cors are:

  • do not perform the "CORS check" (ACAO/ACAC)
  • allow the request to set a new omit origin flag that forces omission of the Origin header
  • require a request to have a policy container specified (via the client is allowed)
  • require the service worker mode to not be all

Because this is such an unsafe mode I added an explanation inline with the other definitions of request modes and a warning about concerns and hand-waves about the client's agent cluster.

Happy to get feedback on this draft!

  • At least two implementers are interested (and none opposed):
    • Mozilla
  • Tests are written and can be reviewed and commented upon at:
    *
  • Implementation bugs are filed:
    • Chromium: …
    • Gecko: …
    • WebKit: …
    • Deno (not for CORS changes): …
  • MDN issue is filed:
    *

Preview | Diff

@annevk
Copy link
Member

annevk commented Nov 11, 2022

Reading your draft I think you and I might have understood the outcome of the meeting differently. Here's what I think:

  • Requests should not be more powerful than "cors" without preflight or "no-cors". You cannot use a DELETE method with this, for instance, or include custom headers.
  • The main benefit of this is not bypassing the CORS check, but bypassing "no-cors"-related checks, such as the upcoming opaque-response blocking and the existing Cross-Origin-Resource-Policy header. (As those are why "no-cors" is not an option and how we plan to make "no-cors" largely safe.)
  • It's also not clear to me that policy container is a drop-in replacement for an environment, although it might fit for a number of cases. That needs a bit more checking I think.

@bvandersloot-mozilla
Copy link
Contributor Author

Reading your draft I think you and I might have understood w3c-fedid/FedCM#320 (comment) differently.

I think we understood the same thing at the end of the meeting, by my understanding diverged with the days between the meeting and when I sat down to draft and my own poor note-taking. I will take another pass to more closely reflect the version you describe in your first two bullets.

It's also not clear to me that policy container is a drop-in replacement for an environment.

I don't think that's quite what I'm doing. I made two distinct changes wrt policy containers:

  • Make the cross-origin resource policy check use the request's policy container, rather than ignoring it and assuming a value of "client" and non-null client. This looked like a bug that needed fixing.
  • Assert that unsafe-no-cors requests do not fallback to a default policy container because none was provided. This is removing a foot-gun of using this version of unsafe-no-cors.

I was thinking that the caller using unsafe-no-cors would construct or have available a global or environment that is the "main process" context and be able to use that. That felt out of the scope of this spec, aside from the warning I added, since the request's client is an argument.

@annevk
Copy link
Member

annevk commented Nov 14, 2022

Make the cross-origin resource policy check use the request's policy container

Right, but you are changing the type of argument here. So all callers would need to start passing in a different argument as well and I guess we're hoping/knowing that we need nothing that isn't available on a policy container?

@bvandersloot-mozilla
Copy link
Contributor Author

Make the cross-origin resource policy check use the request's policy container

Right, but you are changing the type of argument here. So all callers would need to start passing in a different argument as well and I guess we're hoping/knowing that we need nothing that isn't available on a policy container?

Ah, I missed that the algorithm definition is export.

@bvandersloot-mozilla
Copy link
Contributor Author

Alright, I'm about to upload a new version that is more in line with a "stable no-cors" vision.

The diff looks small because some of the algorithms actually just work the way we want when a new enum value is added without any change needed. For example, in no-cors specific checks like "Cross-Origin-Embedder-Policy allows credentials" we are exempt because we are not "no-cors".

I still need to consider the ECMAScript and HTML integration and sort out the neatest way to get caller-control over the presence of the Origin header in unsafe-no-cors. However, I think this benefits from share-early-share-often, if only to keep visibility into the thought process.

fetch.bs Outdated
@@ -1796,13 +1798,27 @@ to not have to set <a for=/>request</a>'s <a for=request>referrer</a>.
<dt>"<code>navigate</code>"
<dd>This is a special mode used only when <a>navigating</a> between documents.

<dt>"<code>unsafe-no-cors</code>"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider naming this something like "host-no-cors" or "ua-no-cors" or something else that indicates what purpose it serves. Just "unsafe" is likely to scare off people who should use it, and not dissuade overconfident people who think they know what they're doing. Since this is only for use in web standards, that'll get caught eventually in spec review, but that could be much later than we want, and a better name could move the right design earlier.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unsafe-no-cors was @annevk's name for it, so I'll defer to him for a renaming decision.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think unsafe is exactly right given that it exposes the contents of the response in the process it was invoked in. It's a name that is supposed to make you ask your peers for advice. I don't think host or ua has that kind of effect, especially since we don't have clearly delineated "host/ua agent clusters".

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, the point of this mode is that it must only be used from the browser process or an equivalently-trusted process, so the response was already exposed there. If it's invoked by that sort of caller, are there any situations where it would still be unsafe?

I have a general rule to avoid "unsafe" and "safe" in naming, since they usually refer to just one kind of safety that was salient to the original author (here, exposure of resource bytes, I think), and future users tend to assume a different kind of safety and so get into trouble.

We could be more specific about what's unsafe instead of trying to name according to the intended caller. E.g. "no-cors-override-exposure-policies". But I suspect that naming according to the intended caller will make it easier to figure out how to maintain this mode's behavior in the future.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I follow the policy that we use for introducing "unsafe" in various places in the web platform. Namely that it requires additional attention. Is easy to lint, etc.

It also very much depends on what happens with the response bytes, how the request is setup, etc.

One point against "unsafe" here might be that it's not useful to web developers as this value is also exposed to them. From that perspective "user-agent-no-cors" is prolly better.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One point against "unsafe" here might be that it's not useful to web developers as this value is also exposed to them. From that perspective "user-agent-no-cors" is prolly better.

Just to double check: do I understand it correctly that this is also going to be exposed to web developers (as Sec-Fetch-Mode=unsafe-no-cors), in addition to browser engineers?

If so, the name shouldn't trigger suspicion by the web developer (who should trust that the spec was written in a careful and thoughtful way, rather than something that the developer has to re-check again), right?

From that perspective "user-agent-no-cors" is prolly better.

Right. user-agent-no-cors would make it do and I think would also address @jyasskin 's point (and @annevk 's, to trigger spec reviewers to look carefully).

FWIW, mediated-no-cors could work too for me, just as a suggestion (user-agent-no-cors works too I think).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah. I think in this case since web developers are not making the unsafe decision it's indeed probably best if they don't see the word unsafe. I think there are other cases though where web developers seeing the word unsafe is good, e.g., unsafe-eval.

I like user-agent-no-cors best still.

fetch.bs Outdated
@@ -1796,13 +1798,27 @@ to not have to set <a for=/>request</a>'s <a for=request>referrer</a>.
<dt>"<code>navigate</code>"
<dd>This is a special mode used only when <a>navigating</a> between documents.

<dt>"<code>unsafe-no-cors</code>"
<dd>This is a special mode for the <a>host environment</a> to use internally to wittingly make
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is "host environment" the right term? It's odd to borrow a Javascript term for something in Fetch that's not integrated in any other way with Javascript infrastructure. I might just use [=user agent=].

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reached for "host environment" because I was talking about agent clusters in the warning and also mentioned the host environment there. I'll change this reference to [=user agent=], but do you think I should leave the reference in the warning alone?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would probably change both to "user agent" or say something about the required memory isolation in the warning, but I don't feel strongly about it. I think we really want something about how trusted the other code in that agent cluster's process is, but I don't think we have the right terms defined for that, and I don't think this change needs to block on thinking through and defining those.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay. I'm changing the warning to be "user agent" as well and mention memory isolation explicitly, rather than directly call in Javascript concepts.

@domfarolino
Copy link
Member

In the documentation for the new mode, we should probably also mention that the request is made from a context that is in some way "detached" from the document/client environment settings object.

Regarding the rest of the spec, this entails at least two things:

  1. Changing how the response process algorithms are scheduled. Right now, for example, the "process response" algorithm is called by queueing a fetch task on either a global object or a parallel queue, which seems to kind of break in the unsafe-no-cors model. We have no notion of a "browser process" in the spec, meaning callers of unsafe-no-cors requests couldn't pass in browser-process-specific scheduling primitives; I think in specs in general, we've been treating the "browser process" as if it were just a bunch of per-caller parallel queues, as we do for much of the navigation and session history infra in HTML. Given that, should we somewhere assert (and also document under the introduction of the new mode) that the associated task destination for unsafe-no-cors fetches must be a parallel queue?
  2. Handling request's client. As mentioned on our last VC, the spec has many assumptions around "client", especially with its interaction with other members. One specific example: a requests' origin defaults to the string "client", and assumes that the request's actual client is non-null in this case, which crashes fetch step 10 if you make an unsafe-no-cors fetch without manually setting request's origin. But that's an awkward requirement, since I think you mentioned your PR has logic that automatically ensures the Origin header isn't sent anyways. This is emblematic of the larger problem: Do you have a plan for handling the many uses of a request's client with this "new" type of request? Should we audit them all, or take a snapshot of the Document's ESO at some point? (As Anne mentioned, request's "client" should be something like a "snapshot" anyways, although I don't know if that's explicit anywhere. Also (aside) it seems weird that a request's "window" is pretending to have access to the actual Window object when we're not fetching on the Document's main thread)

@bvandersloot-mozilla
Copy link
Contributor Author

bvandersloot-mozilla commented Nov 30, 2022

Given that, should we somewhere assert (and also document under the introduction of the new mode) that the associated task destination for unsafe-no-cors fetches must be a parallel queue?

I think so. I'm adding the conditioned assertion into fetch.

RE: the Origin discussion:

This is a shortcoming of this PR and I need to add a new member to request to permit forced Origin header elision.
Generally speaking, I was operating under the assumption that the client would either be a cloned ESO or null, with the necessary other arguments specified, which is already in the spec as a possible argument.

Do you have a plan for handling the many uses of a request's client with this "new" type of request? Should we audit them all, or take a snapshot of the Document's ESO at some point?

I am open to either solution here. I think if there is an expectation that the "client" is a snapshot of some variety, that should be clear and able to be relied upon, so I lean that direction. However, a null client should be applicable here.

Looking through the spec there are only a couple of instances where a null client raises my attention and I am curious how they are handled currently:

Also (aside) it seems weird that a request's "window" is pretending to have access to the actual Window object when we're not fetching on the Document's main thread)

I would expect most uses to have a "window" of "no-window" but do not see a reason to exclude other values.

@bvandersloot-mozilla
Copy link
Contributor Author

Converted to user-agent-no-cors

@domfarolino
Copy link
Member

I was operating under the assumption that the client would either be a cloned ESO or null, with the necessary other arguments specified, which is already in the spec as a possible argument.

When you say "which is already in the spec as a possible argument," do you mean that we expect all unsafe-no-cors consumers to explicitly specify request.policy container and request.referrer policy etc., and so on, for all of the request members that would otherwise be derived implicitly from client (which I guess is null for these kinds of requests)?

@bvandersloot-mozilla
Copy link
Contributor Author

I was operating under the assumption that the client would either be a cloned ESO or null, with the necessary other arguments specified, which is already in the spec as a possible argument.

When you say "which is already in the spec as a possible argument," do you mean that we expect all unsafe-no-cors consumers to explicitly specify request.policy container and request.referrer policy etc., and so on, for all of the request members that would otherwise be derived implicitly from client (which I guess is null for these kinds of requests)?

I meant that this spec already supports a null client, so I assumed this wasn't breaking new ground. If request.client is null, I expect that consumers would have to explicitly specify all arguments that default to "client".

@domfarolino
Copy link
Member

I guess we need to make a decision regarding what to do with client/window in general. I think we don't have the concept of a "snapshotted" ESO at the moment that a user of unsafe-no-cors would pass in, but I guess for discussion we could pretend that this exists, and decide whether that would be a suitable input for requests like this, alongside the normal null.

Snapshotting client

If we decide that snapshotting ESO is a good idea, then I think this means every user of these kinds of requests would be responsible for snapshotting some ESO themselves as the request's client (or maybe the Fetch entrypoint could try and implicitly do it somehow?). Some concerns:

  1. This means the snapshot could of course get out-of-sync with the true ESO on the main thread right when the fetching is started. That seems unavoidable, but probably we should quantify how many checks/steps this impacts: I suppose it would be all of the checks/steps that Fetch does right before going in parallel (ones that are run on the main thread in the usual case)?
  2. There are probably places in Fetch where we use the client not just as a bag of state, but as some interactive thing with an event loop and thing that can handle tasks etc. We should look for such cases, to see if any would cause problems if they suddently start operating on a state snapshot of ESO, instead of the real thing. Perhaps the 3 client usages you provided above might be on this list.

In any case, this approach is simple in for the null client case as you mentioned. We don't have to do anything special that Fetch doesn't already do today, because passing in null as your client would be an explicit decision and I guess you better know what you're doing RE other state. A typical unsafe-no-cors user would probably not pass in null I think, but would use the snapshot.

Always null client

If we decide against the snapshot ESO idea and instead require client and/or window to always be null, then we have to make decisions about all of client-derived state. While null is indeed a valid client value today, its implications are likely not what the typical unsafe-no-cors would want (no referrer policy, CSP bypass, ...) i.e., a lot of that is centralized in policy container, which gets wiped anew in https://fetch.spec.whatwg.org/#ref-for-concept-request-policy-container%E2%91%A0 for null clients, and seems bad for every request like this to endure (see FedCM fetches, one of the motivations for unsafe-no-cors in the first place, which tries to hack together its own CSP check elsewhere).

So if we went this route we'd probably want to assert that an explicit policy container + any other interesting state gets explicitly passed in on the request. That state would likely just be a clone/snapshot of the Document's policy container and additional state, which isn't any better than the snapshotting ESO idea above.

I think if there is an expectation that the "client" is a snapshot of some variety, that should be clear and able to be relied upon, so I lean that direction.

Given all of this, I too lean in the direction of assuming that unless explicitly passed in, the request's client is a snapshot of the associated Document's ESO. But we should gather more feedback, perhaps @annevk has opinions?


Also, it would be great to more explicitly lay-out the integration that this has with #1442 and whatever response-blocking technology already exists (I'm told CORB no longer lives in Fetch, so maybe there is none?), to get a feel for what major behavior change this would entail especially for implementers. Is it simply the fact that unsafe-no-cors requests have "basic" response tainting that exempts them from all of the checks that make no-cors an unsuitable alternative?

fetch.bs Outdated
@@ -4039,7 +4071,9 @@ the request.
<a for="environment settings object">global object</a> is a {{Window}} object; otherwise
"<code>no-window</code>".

<li><p>If <var>request</var>'s <a for=request>origin</a> is "<code>client</code>", then set
<li><p>If <var>request</var>'s <a for=request>origin</a> is "<code>client</code>" and either
<var>request</var>'s <a for=request>mode</a> is not "<code>user-agent-no-cors</code>" or
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is an "or and" in this sentence (and I cannot decide whether it should be "or" or "and")

@bvandersloot-mozilla
Copy link
Contributor Author

Based on conversations at TPAC, cookie layering work looks like it will solve this eventually. Closing this for completeness.

@domfarolino
Copy link
Member

I'm not sure. The motivation for this was some discussion around FedCM fetch requests, of which there are two interesting ones:

  1. The accounts list fetch
  2. The ID assertion fetch

We agreed that the ID assertion fetch can use CORS and can piggyback off of the cookie layering work to send SameSite=None cookies. But the accounts list fetch I think is still somewhat unsolved. That either has to:

  1. Use something like unsafe-no-cors, which will get around ORB blocking of a cross-origin no-cors JSON request/response
  2. Or hack around this by manually changing the initiator of the request to be same-origin with the resource, so ORB won't block it. Maybe this can be justified because the request is "browser-mediated", but maybe not. I think we probably need to discuss this more.

I'll re-open until we discuss the accounts fetch solution more, if that's alright.

@bvandersloot-mozilla
Copy link
Contributor Author

Accidentally closed because I needed to reclaim my main branch, sorry!

@annevk
Copy link
Member

annevk commented Feb 13, 2025

This cannot be reopened so if you want to keep this you need to open a new PR I'm afraid.

tylorjohnson09 added a commit to tylorjohnson09/FedCM that referenced this pull request Jul 24, 2025
<pre class='metadata'>
Title: Federated Credential Management API
Shortname: fedcm
Level: 1
Status: w3c/ED
Group: fedid
TR: http://www.w3.org/TR/fedcm/
ED: https://w3c-fedid.github.io/FedCM/
Prepare for TR: true
Repository: w3c-fedid/FedCM
Editor: Nicolás Peña Moreno, w3cid 103755, Google Inc. https://google.com, [email protected]
Former Editor: Sam Goto, w3cid 50308, Google Inc. https://google.com, [email protected]

Markup Shorthands: markdown yes, biblio yes
Default Biblio Display: inline

Text Macro: FALSE <code>false</code>
Text Macro: TRUE <code>true</code>
Text Macro: RP Relying Party
Text Macro: IDP Identity Provider

Abstract: A Web Platform API that allows users to login to websites with their federated accounts in a privacy-preserving manner.

Test Suite: https://github.com/web-platform-tests/wpt/tree/master/fedcm
</pre>

<pre class=anchors>
spec: ecma262; urlPrefix: https://tc39.github.io/ecma262/
    type: dfn
        text: internal method; url: sec-ordinary-object-internal-methods-and-internal-slots

spec: credential-management-1; urlPrefix: https://w3c.github.io/webappsec-credential-management/
    type: dfn
        text: same-origin with its ancestors; url: same-origin-with-its-ancestors
    type: dfn
        text: requires user mediation; url: origin-requires-user-mediation
spec: webdriver; urlPrefix: https://w3c.github.io/webdriver/
    type: dfn
        text: endpoint node; url: dfn-endpoint-node
        text: extension capability; url: dfn-extension-capability
        text: getting a property; url: dfn-getting-properties
        text: matching capabilities; url: dfn-matching-capabilities
        text: no such alert; url: dfn-no-such-alert
        text: error code; url: dfn-error-code
        text: validating capabilities; url: dfn-validate-capabilities
spec: webappsec-fetch-metadata; urlPrefix: https://w3c.github.io/webappsec-fetch-metadata/
    type: dfn
        text: Directly User-Initiated Requests; url: directly-user-initiated
spec: login-status; urlPrefix: https://w3c-fedid.github.io/login-status
    type: dfn
        text: logged-in; url: logged-in
        text: logged-out; url: logged-out
        text: unknown; url: unknown
        text: get the login status; url: get-the-login-status
        text: set the login status; url: set-the-login-status
</pre>

<pre class=link-defaults>
spec:infra; type:dfn; text:list
spec:infra; type:dfn; text:user agent
spec:html; type:dfn; for:environment settings object; text:global object
spec:html; type:dfn; for:html-origin-def; text:origin
spec:webidl; type:dfn; text:resolve
spec:webdriver2; type:dfn; text:error
spec:webdriver2; type:dfn; text:remote end steps
spec:fetch; type:dfn; for:/; text:response
spec:css-color-5; type:type; text:<color>
spec:html; type:dfn; text:allowed to use
</pre>

<style>
dl.domintro dt {
    font-family: Menlo, Consolas, "DejaVu Sans Mono", Monaco, monospace;

    padding-top: 0.5em;
    padding-bottom: 1em;
}
dl.domintro dt a {
    color: inherit; border-bottom-style: none;
}
dl.domintro dt code {
    font-size: inherit;
}
.idp-normative-text {
    background-color: rgba(165, 42, 42, 0.3);
    margin: 16px 0px;
    padding: 8px;
    border-left: 8px solid brown;
}

/* temporary fixes to the typogram diagrams
   to support dark mode properly */
script + svg :is(polygon, line, rect):not(.grid) {
  stroke: currentcolor;
}
script + svg :is(polygon, text) {
  fill: currentcolor;
}
</style>

<script src="https://w3c-fedid.github.io/FedCM/static/underscore-min.js"></script>
<script src="https://w3c-fedid.github.io/FedCM/static/raphael.min.js"></script>
<script src="https://w3c-fedid.github.io/FedCM/static/webfont.js"></script>
<script src="https://w3c-fedid.github.io/FedCM/static/typogram.js"></script>

<!-- ============================================================ -->
# Introduction # {#introduction}
<!-- ============================================================ -->

*This section is non-normative.*

As the web has evolved there have been ongoing privacy-oriented changes
(e.g [Safari](https://webkit.org/blog/10218/full-third-party-cookie-blocking-and-more/),
[Firefox](https://blog.mozilla.org/blog/2019/09/03/todays-firefox-blocks-third-party-tracking-cookies-and-cryptomining-by-default/),
[Chrome](https://blog.google/products/chrome/privacy-sustainability-and-the-importance-of-and/))
and changes to the underlying privacy principles (e.g. [[PRIVACY-MODEL]]).

With this evolution, fundamental assumptions of the web
platform are being redefined or removed. Access to cookies in a third-party
context are one of those assumptions. While overall good for the
web, the third-party cookie deprecation removes a fundamental building block
used by certain designs of federated identity.

The Federated Credential Management API aims to bridge the gap for the
federated identity designs which relied on third-party cookies.
The API provides the primitives needed to support federated identity when/where
it depends on third-party cookies, from sign-in to sign-out and revocation.

In order to provide the federated identity primitives without the use of
third-party cookies the API places the [=user agent=] as a mediator between a
<dfn><abbr title="Relying Party">RP</abbr></dfn> (website that requests user information for
federated sign in) and an <dfn><abbr title="Identity Provider">IDP</abbr></dfn> (website that provides
user information for federated sign in). This mediation requires user
permission before allowing the [=RPs=] and [=IDPs=] to know about their
connection to the user.

The specification leans heavily on changes in the [=user agent=] and [=IDP=]
and minimally on the [=RP=]. The FedCM API provides a way to fetch tokens.

<div class=example>
Example showing how a website allowing for a single logged in account
could be implemented.

```html
<html>
<head>
  <title>Welcome to my Website</title>
</head>
<body>
  <button onclick="login()">Login with idp.example</button>

  <script>
  let nonce;
  async function login() {
    try {
      // Assume there is a method returning a random number. Store the value in a variable which can
      // later be used to check against the value in the token returned.
      nonce = random();
      // Prompt the user to select an account from the IDP to use for
      // federated login within the RP. If resolved successfully, the Promise
      // returns an IdentityCredential object from which the |token| can be
      // extracted. This is an opaque string passed from the IDP to the RP.
      let token = await navigator.credentials.get({
        identity: {
          providers: [{
            configURL: "https://idp.example/manifest.json",
            clientId: "123",
            nonce: nonce,
          }]
        }
      });
    } catch(e) {
      // The FedCM call was not successful.
    }
  }
  </script>
</body>
</html>
```
</div>


At a high level, the Federated Credential Management API works by the
intermediation of cooperating [=IDP=]s and [=RP=]s.

The [[#idp-api]] defines a set of HTTP APIs that [=IDP=]s expose as well as the entry points in the
[[#browser-api]] that they can use.

<script type="text/typogram">
+-----------+                  +-----------+                      +-----------+
|           |                  |           |                      |           |
|  Relying  |                  |   User    |                      | Identity  |
|   Party   |                  |   Agent   |                      | Provider  |
|           |                  |           |                      |           |
|           |                  | Federated |                      |           |
|           |   +----------->*-+ Credential|     +------------->*-+ Well-Known|
|           |   |              | Management|     |                |           |
|           |   |              |    API    |     +------------->*-+ Config    |
|           |   |              |           |     |                |           |
|           |   |              |           |     +------------->*-+ Accounts  |
|           |   |              |           |     |                |           |
|           |   |              |           |     +------------->*-+ Assertion |
|           |   |              |           |     |                |           |
|           |   |              |           |     |                |           |
| +-------+ |   |              | +-------+ |     |                |           |
| | JS    +-+---+              | + HTTP  +-+-----+                |           |
| +-------+ |                  | +-------+ |                      |           |
|           |                  |           |                      |           |
|           |                  |           |                      |           |
+-----------+                  +-----------+                      +-----------+
</script>

<div class="issue" heading="extension">
An extension spec may add a client metadata endpoint between accounts and assertion:
<script type="text/typogram">
|           |   |              |           |     +------------->*-+ Accounts  |
|           |   |              |           |     |                |           |
|           |   |              |           |     +------------->*-+ Client    |
|           |   |              |           |     |                | Metadata  |
|           |   |              |           |     |                |           |
|           |   |              |           |     +------------->*-+ Assertion |
|           |   |              |           |     |                |           |
</script>
</div>

The user agent intermediates in a manner that makes it impractical for the
API to be used for tracking purposes, while preserving the functionality of
identity federation.

<script type="text/typogram">
    Relying                             User                            Identity
    Party                               Agent                           Provider

      |                                   |                                 |
      | "navigator.credentials.get({    " | "(1) The RP invokes the API."   |
      | "  identity: {                  " |                                 |
      | "    providers: [{              " |                                 |
      | "      configURL: 'config.json'," |                                 |
      | "      clientId: clientId,      " |                                 |
      | "      nonce: nonce,            " |                                 |
      | "    }]                         " |                                 |
      | "  }                            " |                                 |
      | "})                             " |                                 |
      |                                   |                                 |
      |---------------------------------->|                                 |
      |                                   |                                 |
      |                                   |                                 |
      | "(2) From the configURL, the    " | "GET /.well-known/web-identity" |
      | "browser makes two requests     " |-------------------------------->|
      | "in parallel.                   " |                                 |
      |                                   | "GET /config.json"              |
      |                                   |-------------------------------->|
      |                                   |                                 |
      | "(3) The IdP responds with a    " |                                 |
      | "well-known file and a          " |                                 |
      | "config file.                   " |                                 |
      |                                   |                                 |
      |                                   |                                 |
      |                                   |                                 |
      | "The well-known file            " | "Well-Known file"               |
      | "contains a list of valid       " |<--------------------------------| "{"
      | "config URLs.                   " |                                 |   "provider_urls: [ ... ]"
      |                                   |                                 | "}"
      |                                   |                                 |
      | "The config file contains       " | "Config file"                   |
      | "information about the IdP.     " |<--------------------------------| "{"
      |                                   |                                 |   "id_assertion_endpoint: ...,"
      |                                   |                                 |   "accounts_endpoint: /accounts,"
      |                                   |                                 |   "client_metadata_endpoint: ...,"
      |                                   |                                 |   "branding: ...,"
      |                                   |                                 | "}"
      |                                   |                                 |
      | "(4) The browser proceeds to    " | "GET /accounts"                 |
      | "fetch the list of accounts     " | "Cookie: name=value"            |
      | "that the user is logged in     " |-------------------------------->|
      | "to.                            " |<--------------------------------| "{"
      |                                   |                                 |   "accounts: [ ... ]"
      |                                   |                                 | "}"
      |                                   |                                 |
      |                                   |                                 |
      |                     +-------------+ "(5) With all of this, the    " |
      |                     |             | "browser asks for the user's  " |
      |                     |             | "permission to sign-in to the " |
      |  "account chooser"  |             | "RP with the IdP's account.   " |
      |                     |             |                                 |
      |                     |             |                                 |
      |                     +------------>|                                 |
      |                                   |                                 |
      |                                   |                                 |
      |                                   |                                 |
      | "(6) Once the user selects an   " | "POST /assertion"               |
      | "account and permission, the    " | "client_id, cookies, account"   |
      | "browser fetches the token.     " |-------------------------------->|
      |                                   |<--------------------------------| "{"
      |                                   |                                 |   "token: ...,"
      |                                   |                                 | "}"
      |                                   |                                 |
      |                "{ token }"        | "(7) Which is then ultimately " |
      |<----------------------------------| "used to resolve the promise. " |
      |                                   |                                 |
      |                                   |                                 |
     -+-                                 -+-                               -+-
</script>

<div class="issue" heading="extension">
The following could be added to an extension spec:

<script type="text/typogram">
      |                                   |                                 |
      | "(4.5) The browser then         " | "GET /client_metadata"          |
      | "fetches metadata about the     " | "client_id"                     |
      | "Relying Party.                 " |-------------------------------->|
      |                                   |<--------------------------------| "{"
      |                                   |                                 |   "terms_of_service_url: ...,"
      |                                   |                                 |   "privacy_policy_url: ...,"
      |                                   |                                 | "}"
      |                                   |                                 |
</script>
</div>

<!-- ============================================================ -->
# The Browser API # {#browser-api}
<!-- ============================================================ -->

The Browser API exposes APIs to [=RP=]s and [=IDP=]s to call and intermediates
the exchange of the user's identity.

The Sign-up/Sign-in API is used by the [=RP=]s to ask the browser
to intermediate the relationship with the [=IDP=] and the
provisioning of a token.

NOTE: The [=RP=] makes no delineation between Sign-up and Sign-in, but
rather calls the same API indistinguishably.

If all goes well, the Relying Party receives back an {{IdentityCredential}}
which contains a token it can use to authenticate the user.

<div class=example>
```js
const credential = await navigator.credentials.get({
  identity: {
    providers: [{
      configURL: "https://idp.example/manifest.json",
      clientId: "123",
    }]
  }
});
```
</div>

When fetches are sent with cookies, unpartitioned
[SameSite](https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html#name-the-samesite-attribute-2)=None
cookies are included. It doesn't introduce security issues on the API even when third-party cookies are otherwise
disabled because the [=RP=] cannot inspect the results from the fetches on its own (i.e., the browser mediates what
the [=RP=] can receive).

<!-- ============================================================ -->
## The connected accounts set ## {#browser-connected-accounts-set}
<!-- ============================================================ -->

Each [=user agent=] has a global <dfn>connected accounts set</dfn>, an initially empty
[=ordered set=]. Its [=list/items=] are triples of the form (|rp|, |idp|, |account|) where |rp| is
the [=/origin=] of the [=RP=], |idp| is the [=/origin=] of the [=IDP=], and |account| is a string representing
an account identifier. It represents the set of triples such that the user has used FedCM to login to
the |rp| via the |idp| |account|.

Issue: the [=connected accounts set=] should be double keyed in the [=RP=] (i.e., it should include
both the requester and the embedder, or in other words the iframe and the top-level). Otherwise the
top-level's state could be used and modified by the embedder, which introduces leaks and unwanted
cross-origin communication.

If a user clears browsing data for an |origin| (cookies, localStorage, etc.), the user agent MUST
[=list/remove=] all triples with an [=/origin=] matching the |origin| from <a>connected accounts set</a>.

<div algorithm>
To <dfn>compute the connected account key</dfn> given an {{IdentityProviderConfig}} |provider|, an
{{IdentityProviderAccount}} |account|, and a |globalObject|, run the following steps. It returns a
triple of the form (rp, idp, account).
    1. Let |configUrl| be the result of running [=parse url=] with |provider|'s
        {{IdentityProviderConfig/configURL}} and |globalObject|.
    1. Let |idpOrigin| be the [=url/origin=] corresponding to |configUrl|.
    1. Let |rpOrigin| be |globalObject|'s [=associated Document=]'s [=Document/origin=].
    1. Let |accountId| be |account|'s {{IdentityProviderAccount/id}}.
    1. Return (|rpOrigin|, |idpOrigin|, |accountId|).
</div>

<div algorithm>
When asked whether an {{IdentityProviderAccount}} |account| is
<dfn>eligible for auto reauthentication</dfn> given an {{IdentityProviderConfig}} |provider| and a
|globalObject|, run the following steps. This returns a boolean.
    1. If |account| [=map/contains=] {{IdentityProviderAccount/approved_clients}} and
        |account|'s {{IdentityProviderAccount/approved_clients}} does not [=list/contain=]
        |provider|'s {{IdentityProviderConfig/clientId}}, return false.
    1. Let |triple| be the result of running [=compute the connected account key=] given |provider|,
        |account|, and |globalObject|.
    1. Return whether [=connected accounts set=] [=list/contains=] |triple|.
</div>

<div algorithm="compute the connection status">
When asked to <dfn>compute the connection status</dfn> given an {{IdentityProviderAccount}}
|account|, an {{IdentityProviderConfig}} |provider| and a |globalObject|, run the following steps.
This returns <dfn for="compute the connection status">connected</dfn> or
<dfn for="compute the connection status">disconnected</dfn>.
    1. If |account| [=map/contains=] {{IdentityProviderAccount/approved_clients}}:
        1. If |account|'s {{IdentityProviderAccount/approved_clients}} [=list/contains=]|provider|'s
            {{IdentityProviderConfig/clientId}}, return [=compute the connection status/connected=].
        1. Return [=compute the connection status/disconnected=].
    1. Let |triple| be the result of running [=compute the connected account key=] given |provider|,
        |account|, and |globalObject|.
    1. If [=connected accounts set=] [=list/contains=] |triple|, return
        [=compute the connection status/connected=].
    1. Return [=compute the connection status/disconnected=].
</div>

<div algorithm>
To <dfn>create a connection between the RP and the IdP account</dfn> given an
{{IdentityProviderConfig}} |provider|, an {{IdentityProviderAccount}} |account|, and a
|globalObject| (the [=RP=]'s), run the following steps:
    1. Let |configUrl| be the result of running [=parse url=] with |provider|'s
        {{IdentityProviderConfig/configURL}} and |globalObject|.
    1. Let |idpOrigin| be the [=url/origin=] corresponding to |configUrl|.
    1. Let |rpOrigin| be |globalObject|'s [=associated Document=]'s [=Document/origin=].
    1. Let |accountId| be |account|'s {{IdentityProviderAccount/id}}.
    1. Let |triple| be (|rpOrigin|, |idpOrigin|, |accountId|).
    1. [=set/Append=] |triple| to [=connected accounts set=].
</div>

<div algorithm>
To <dfn>remove a connection</dfn>: given |accountId|, |rpOrigin|, and |idpOrigin|, run the
following steps. It returns whether the |accountId| connection was successfully removed.
    1. Let |triple| be (|rpOrigin|, |idpOrigin|, |accountId|).
    1. If [=connected accounts set=] [=list/contains=] |triple|:
        1. [=list/Remove=] |triple| from the [=connected accounts set=].
        1. Return true.
    1. Return false.
</div>

<div algorithm>
To <dfn>remove all connections</dfn>: given |rpOrigin| and |idpOrigin|, run the following steps:
    1. For every (|rp|, |idp|, <var ignore="">accountId</var>) |triple| in the
        [=connected accounts set=]:
        1. If |rp| equals |rpOrigin| and |idp| equals |idpOrigin|, [=list/remove=] |triple| from the
            [=connected accounts set=].
</div>

<!-- ============================================================ -->
## The IdentityCredential Interface ## {#browser-api-identity-credential-interface}
<!-- ============================================================ -->

This specification introduces a new type of {{Credential}}, called an {{IdentityCredential}}:

<pre class="idl">
  dictionary IdentityCredentialDisconnectOptions : IdentityProviderConfig {
    required USVString accountHint;
  };

  [Exposed=Window, SecureContext]
  interface IdentityCredential : Credential {
    static Promise&lt;undefined&gt; disconnect(IdentityCredentialDisconnectOptions options);
    readonly attribute USVString? token;
    readonly attribute boolean isAutoSelected;
    readonly attribute USVString configURL;
  };
</pre>

<dl>
    :   <b>{{Credential/id}}</b>
    ::  The {{Credential/id}}'s attribute getter returns the empty string.
    :   <b>{{IdentityCredential/token}}</b>
    ::  The {{IdentityCredential/token}}'s attribute getter returns the value it is set to.
        It represents the minted {{IdentityAssertionResponse/token}} provided by the [=IDP=].
    :   <b>{{IdentityCredential/isAutoSelected}}</b>
    ::  {{IdentityCredential/isAutoSelected}}'s attribute getter returns the value it is
        set to. It represents whether the user's identity credential was automatically selected when
        going through the UI flow which resulted in this {{IdentityCredential}}.
    : <b>{{IdentityCredential/configURL}}</b>
    :: The {{IdentityCredential/configURL}}'s attribute getter returns the value it is set to.
        It represents the config URL corresponding to the [=IDP=] which issued this credential.
    :   <b>{{Credential/[[type]]}}</b>
    ::  The {{IdentityCredential}}'s {{Credential/[[type]]}}'s value is "<b>identity</b>".
    :   <b>{{Credential/[[discovery]]}}</b>
    ::  The {{IdentityCredential}}'s {{Credential/[[discovery]]}}'s value is
        {{Credential/[[discovery]]/remote}}.
</dl>

The main entrypoint in this specification is through the entrypoints exposed
by the [[CM]] API.

<!-- ============================================================ -->
### The disconnect method ### {#browser-api-identity-credential-disconnect}
<!-- ============================================================ -->

<div algorithm="identity-credential-disconnect">
When the static {{IdentityCredential/disconnect}} method is invoked, given an
{{IdentityCredentialDisconnectOptions}} |options|, perform the following steps:

    1. Let |globalObject| be the [=current global object=].
    1. Let |document| be |globalObject|'s [=associated Document=].
    1. If |document| is not [=allowed to use=] the [=identity-credentials-get=]
        [=policy-controlled feature=], throw a "{{NotAllowedError}}" {{DOMException}}.
    1. Let |promise| be a new {{Promise}}.
    1. [=In parallel=], [=attempt to disconnect=] given |options|, |promise|, and |globalObject|.
    1. Return |promise|.
</div>

<div algorithm>
When asked to <dfn>attempt to disconnect</dfn> given an {{IdentityCredentialDisconnectOptions}}
|options|, a {{Promise}} |promise|, and a |globalObject|, perform the following steps:

    1. Assert: these steps are running [=in parallel=].
    1. Let |configUrl| be the result of running [=parse url=] with |options|'s
        {{IdentityProviderConfig/configURL}} and |globalObject|.
    1. If |configUrl| is failure, [=reject=] |promise| with an "{{InvalidStateError}}"
        {{DOMException}}.
    1. Run a [[!CSP]] check with a [[CSP#directive-connect-src|connect-src]] directive on the URL
        passed as |configUrl|. If it fails, [=reject=] |promise| with a "{{NetworkError}}"
        {{DOMException}}.
    1. If there is another pending {{IdentityCredential/disconnect}} call for this |globalObject|
        (e.g., it has not yet thrown an exception or its associated {{Promise}} has not yet been
        resolved), [=reject=] |promise| with a "{{NetworkError}}" {{DOMException}}.
    1. If |configUrl| is not a [=potentially trustworthy origin=], [=reject=] |promise| with a
        "{{NetworkError}}" {{DOMException}}.
    1. If the user has disabled the FedCM API on the |globalObject|, [=reject=] |promise| with a
        "{{NetworkError}}" {{DOMException}}.
    1. If there does not exist an account |account| such that [=connected accounts set=]
        [=list/contains=] the result of [=compute the connected account key=] given |account|,
        |options|, and |globalObject|, then [=reject=] |promise| with a "{{NetworkError}}"
        {{DOMException}}. This check can be performed by iterating over the
        [=connected accounts set=] or by keeping a separate data structure to make this lookup fast.
    1. Let |config| be the result of running [=fetch the config file=] with
        |provider| and |globalObject|.
    1. If |config| is failure, [=reject=] |promise| with a "{{NetworkError}}" {{DOMException}}.
    1. Let |disconnectUrl| be the result of [=computing the manifest URL=] given |provider|,
        |config|.{{IdentityProviderAPIConfig/disconnect_endpoint}}, and |globalObject|.
    1. If |disconnectUrl| is failure, [=reject=] |promise| with a "{{NetworkError}}"
        {{DOMException}}.
    1. [=Send a disconnect request=] with |disconnectUrl|, |options|, and |globalObject|, and let
        |result| be the result.
    1. Let |idpOrigin| be the [=url/origin=] corresponding to |configUrl|.
    1. Let |rpOrigin| be |globalObject|'s [=associated Document=]'s [=Document/origin=].
    1. If |result| is failure:
        1. [=Remove all connections=] given |rpOrigin| and |idpOrigin|.
        1. [=Reject=] |promise| with a "{{NetworkError}}" {{DOMException}}.
        1. Return.
    1. Let |accountId| be |result| (note that it is not failure).
    1. [=Remove a connection=] using |accountId|, |rpOrigin|, and |idpOrigin|, and let
        |wasAccountRemoved| be the result.
    1. If |wasAccountRemoved| is false, [=remove all connections=] given |rpOrigin| and |idpOrigin|.
    1. [=Resolve=] |promise|.
</div>

<!-- ============================================================ -->
#### Disconnect request #### {#disconnect-request}
<!-- ============================================================ -->

The [=send a disconnect request=] algorithm sends a request to disconnect an account that has
previously been used for federated login in the [=RP=].

<div algorithm>
When asked to <dfn>send a disconnect request</dfn>, given a <a spec=url for=/>URL</a>
|disconnectUrl|, and {{IdentityCredentialDisconnectOptions}} |options|, and a |globalObject|,
perform the following steps. This returns an {{USVString}} or failure.

    1. Let |requestBody| be the result of running [=urlencoded serializer=] with a list containing:
        1. ("client_id", |options|'s {{IdentityProviderConfig/clientId}})
        1. ("account_hint",  |options|'s {{IdentityCredentialDisconnectOptions/accountHint}})
    1. Let |request| be a new <a spec=fetch for=/>request</a> as follows:

        :  [=request/url=]
        :: |disconnectUrl|
        :  [=request/method=]
        :: "POST"
        :  [=request/body=]
        :: the [=UTF-8 encode=] of |requestBody|
        :  [=request/redirect mode=]
        :: "error"
        :  [=request/client=]
        :: null
        :  [=request/window=]
        :: "no-window"
        :  [=request/service-workers mode=]
        :: "none"
        :  [=request/destination=]
        :: "webidentity"
        :  [=request/origin=]
        :: |globalObject|'s [=associated document=]'s [=Document/origin=]
        :  [=request/header list=]
        :: a [=list=] containing a single [=header=] with [=header/name=] set to `Accept` and
            [=header/value=] set to `application/x-www-form-urlencoded`
        :  [=request/credentials mode=]
        :: "include"
        :  [=request/mode=]
        :: "cors"

    1. Let |accountId| be null.
    1. [=Fetch request=] with |request| and |globalObject|, and with
        <var ignore>processResponseConsumeBody</var> set to the following steps given a
        <a spec=fetch for=/>response</a> |response| and |responseBody|:
        1. Let |json| be the result of [=extract the JSON fetch response=] from |response| and
            |responseBody|.
        1. [=converted to an IDL value|Convert=] |json| to a {{DisconnectedAccount}}, |account|.
        1. If one of the previous two steps threw an exception, set |accountId| to failure
            and return.
        1. Set |accountId| to |account|'s {{DisconnectedAccount/account_id}}.
    1. Wait for |accountId| to be set.
    1. Return |accountId|.
</div>

<xmp class="idl">
dictionary DisconnectedAccount {
  required USVString account_id;
};
</xmp>

<!-- ============================================================ -->
### The CredentialRequestOptions ### {#browser-api-credential-request-options}
<!-- ============================================================ -->

This section defines the dictionaries passed into the JavaScript call:

<div class=example>
```js
const credential = await navigator.credentials.get({
  identity: { // IdentityCredentialRequestOptions
    providers: [{  // sequence<IdentityCredentialRequestOptions>
      configURL: "https://idp.example/manifest.json", // IdentityProviderConfig.configURL
      clientId: "123", // IdentityProviderConfig.clientId
      nonce: "nonce" // IdentityProviderConfig.nonce
    }]
  }
});
```
</div>

This specification introduces an extension to the {{CredentialRequestOptions}} object:

<pre class="idl">
  partial dictionary CredentialRequestOptions {
    IdentityCredentialRequestOptions identity;
  };
</pre>

The {{IdentityCredentialRequestOptions}} contains a list of
{{IdentityProviderConfig}}s that the [=RP=] supports and has
pre-registered with (i.e. the [=IDP=] has given the [=RP=] a `clientId`).
The {{IdentityCredentialRequestOptions}} also contains an
{{IdentityCredentialRequestOptionsContext}}, which the user agent can use to
provide a more meaningful dialog to users, and an
{{IdentityCredentialRequestOptionsMode}}, which the user agent can use to
specify different behaviors or dialog types.

<xmp class=idl>
enum IdentityCredentialRequestOptionsContext {
  "signin",
  "signup",
  "use",
  "continue"
};

enum IdentityCredentialRequestOptionsMode {
  "active",
  "passive"
};

dictionary IdentityCredentialRequestOptions {
  required sequence<IdentityProviderRequestOptions> providers;
  IdentityCredentialRequestOptionsContext context = "signin";
  IdentityCredentialRequestOptionsMode mode = "passive";
};
</xmp>

Each {{IdentityProviderConfig}} represents an [=IDP=] that
the [=RP=] supports (e.g. that it has a pre-registration agreement with).

<xmp class=idl>
dictionary IdentityProviderConfig {
  required USVString configURL;
  required USVString clientId;
};

dictionary IdentityProviderRequestOptions : IdentityProviderConfig {
  USVString nonce;
  DOMString loginHint;
  DOMString domainHint;
  sequence<USVString> fields;
  any params;
};
</xmp>

<dl>
    :   <b>{{IdentityProviderConfig/configURL}}</b>
    ::  The URL of the configuration file for the identity provider.
    :   <b>{{IdentityProviderConfig/clientId}}</b>
    ::  The {{id_assertion_endpoint_request/client_id}} provided to the [=RP=] out of band by the [=IDP=]
    :   <b>{{IdentityProviderRequestOptions/nonce}}</b>
    ::  A random number of the choice of the [=RP=]. It is generally used to associate a client
        session with a {{IdentityAssertionResponse/token}} and to mitigate replay attacks.
        Therefore, this value should have sufficient entropy such that it would be hard to guess.
    :   <b>{{IdentityProviderRequestOptions/loginHint}}</b>
    ::  A string representing the login hint corresponding to an account which the RP wants the user
        agent to show to the user. If provided, the user agent will not show accounts which do not
        match this login hint value. It generally matches some attribute from the desired
        {{IdentityProviderAccount}}.
    :   <b>{{IdentityProviderRequestOptions/domainHint}}</b>
    ::  A string representing the domain hint corresponding to a domain which the [=RP=] is
        interested in, or "any" if the [=RP=] wants any account associated with at least one domain
        hint. If provided, the user agent will not show accounts which do not match the domain hint
        value.
</dl>

<!-- ============================================================ -->
### The <code>\[[DiscoverFromExternalSource]](origin, options, sameOriginWithAncestors)</code> internal method ### {#browser-api-rp-sign-in}
<!-- ============================================================ -->

The {{Credential/[[DiscoverFromExternalSource]](origin, options, sameOriginWithAncestors)}}
algorithm runs in parallel inside [[credential-management#algorithm-request]] to request
credentials and returns an {{IdentityCredential}} or an error.

This [=internal method=] accepts three arguments:

<dl dfn-type="argument" dfn-for="IdentityCredential/[[DiscoverFromExternalSource]](origin, options, sameOriginWithAncestors)">
    :   <dfn>origin</dfn>
    ::  This argument is the [=relevant settings object=]'s
         [=environment settings object/origin=], as determined by the
         calling {{CredentialsContainer/get()}} implementation, i.e.,
         {{CredentialsContainer}}'s <a abstract-op>Request a `Credential`</a>
         abstract operation.
    :   <dfn>options</dfn>
    ::  This argument is a {{CredentialRequestOptions}} object whose
        {{CredentialRequestOptions/identity}} member [=map/exists=].
    :   <dfn>sameOriginWithAncestors</dfn>
    ::  This argument is a Boolean value which is [TRUE] if and only if the
         caller's [=environment settings object=] is
         [=same-origin with its ancestors=]. It is [FALSE] if caller is cross-origin.

        Note: Invocation of this [=internal method=] indicates that it was allowed by
        [=permissions policy=], which is evaluated at the [[!CREDENTIAL-MANAGEMENT-1]] level.
        See [[#permissions-policy-integration]]. As such,
            <var ignore=''>sameOriginWithAncestors</var> is unused.

</dl>

The <var ignore="">options</var>.{{CredentialRequestOptions/signal}} is used as an abort signal for the
requests.

<div algorithm="[[DiscoverFromExternalSource]](origin, options, sameOriginWithAncestors)">
When the {{IdentityCredential}}'s
<dfn for="IdentityCredential" method>\[[DiscoverFromExternalSource]](origin, options, sameOriginWithAncestors)</dfn>
algorithm is invoked, the user agent MUST execute the following steps. This returns an
{{IdentityCredential}} (or throws an error to the caller).

    1. Assert: These steps are running [=in parallel=].
    1. If
        |options|["{{CredentialRequestOptions/identity}}"]["{{IdentityCredentialRequestOptions/providers}}"]
        is [=list/empty=], [=queue a global task=] on the [=DOM manipulation task source=] given
        |globalObject| to throw a new "{{NetworkError}}" {{DOMException}}.

        Note: The |globalObject| is not currently passed onto the
        {{Credential/[[DiscoverFromExternalSource]](origin, options, sameOriginWithAncestors)}}
        algorithm. See <a href="https://github.com/w3c/webappsec-credential-management/issues/210">issue</a>.
    1. Let |providerList| be |options|["{{CredentialRequestOptions/identity}}"]["{{IdentityCredentialRequestOptions/providers}}"].
    1. Let |credential| be the result of running [=create an IdentityCredential=] with |providerList|,
        |options|, and |globalObject|.

        Note: The |globalObject| is not currently passed onto the
        {{Credential/[[DiscoverFromExternalSource]](origin, options, sameOriginWithAncestors)}}
        algorithm. See <a href="https://github.com/w3c/webappsec-credential-management/issues/210">issue</a>.

    1. If |credential| is a pair:
        1. Let |throwImmediately| be the value of the second element of the pair.
        1. The user agent SHOULD wait a random amount of time
            before the next step if all of the following conditions hold:
            * |throwImmediately| is false
            * The <dfn>promise rejection delay</dfn> was not disabled by
                [=setdelayenabled|user agent automation=]
            * The user agent has not implemented another way to prevent
                exposing to the RP whether the user has an account logged
                in to the RP

            Note: The intention here is as follows. If the the promise was resolved immediately,
                then an RP could infer that no dialog was shown because the promise was
                resolved quickly, after just the network delay. A shown dialog implies
                that the user is logged in to one or more accounts of the IDP. To prevent
                this information leakage, especially without user confirmation, this delay is specified.
                However, UAs may have different UI approaches here and prevent it in a different way.
        1. [=Queue a global task=] on the [=DOM manipulation task source=]
            to throw a new "{{NetworkError}}" {{DOMException}}.
    1. Otherwise, return |credential|.
</div>

<!-- ============================================================ -->
### Create an IdentityCredential ### {#create-identity-credential}
<!-- ============================================================ -->

The <a>create an IdentityCredential</a> algorithm invokes the various FedCM fetches, shows the user
agent UI, and creates the {{IdentityCredential}} that is then returned to the [=RP=].

<div algorithm="create an IdentityCredential">
To <dfn>create an IdentityCredential</dfn> given a [=sequence=] of  {{IdentityProviderRequestOptions}}
|providerList|, a {{CredentialRequestOptions}} |options|, and a
|globalObject|, run the following steps. This returns an {{IdentityCredential}}
or a pair (failure, bool), where the bool indicates whether to skip delaying
the exception thrown.
    1. Assert: These steps are running [=in parallel=].
    1. Let |mode| be |options|'s {{IdentityCredentialRequestOptions/mode}}.
    1. If |mode| is {{IdentityCredentialRequestOptionsMode/active}}:
        1. If |providerList|'s [=list/size=] is not equal to 1, return (failure, true).
        1. Assert: |globalObject| is a {{Window}}.
        1. If |globalObject| does not have [=transient activation=], return (failure, true).
        1. Otherwise, if there is a pending request where {{IdentityCredentialRequestOptionsMode}} is
            {{IdentityCredentialRequestOptionsMode/passive}} on |globalObject|'s [=Window/navigable=]'s
            [=navigable/top-level traversable=] or on any of its descendants, reject the pending
            request with a "{{NetworkError}}" {{DOMException}}.
    1. The user agent MAY wait an arbitrary amount of time before continuing with the next steps.
        The user agent MAY also return (failure, false) at this point or after some arbitrary wait.
        The user agent MAY also set |providerList| to a subset of itself after some arbitrary wait.

        <div class="note">
        NOTE: For example, the user agent could do any of the following:
            * Show an identity provider selector and only proceed once
                  the user confirms their desire to use an identity provider.
            * Provide a button in the URL bar and wait for user input
                  before continuing. 
            * Use previous user behavior to determine not to show any
                  UI to the user and silently reject the request.
        </div>
    1. Let |mediation| be |options|'s {{CredentialRequestOptions/mediation}}.
    1. Let |providerMap| be a new [=map=].
    1. For each |provider| in |providerList|:
        Note: The fetches performed in these steps to populate |providerMap| can be performed at the
            same time, e.g., the second [=IDP=]'s fetches can be started before the first ones finish,
            since these are indepedent.
        1. Let |providerOrigin| be the [=/origin=] of |provider|'s {{IdentityProviderConfig/configURL}}.
        1. If |providerMap| [=map/contains=] |providerOrigin|, return (failure, true).
        1. Let |loginStatus| be the result of [=get the login status=] with |providerOrigin|.
        1. If |loginStatus| is [=unknown=], a user agent MAY set it to [=logged-out=].
        1. If |loginStatus| is [=logged-out=]:
            1. If |mode| is {{IdentityCredentialRequestOptionsMode/active}}:
                1. Let |result| be the result of running
                    [=fetch the config file and show an IDP login dialog=] with
                    |provider| and |globalObject|.
                1. If |result| is failure, return (failure, true).
            1. Otherwise, set |providerMap|[|providerOrigin|] to "logged-out" and [=continue=].
        1. Let |requiresUserMediation| be |providerOrigin|'s [=requires user mediation=].
        1. If |requiresUserMediation| is true and |mediation| is
            "{{CredentialMediationRequirement/silent}}", [=continue=].
        1. Let |config| be the result of running [=fetch the config file=] with
            |provider| and |globalObject|.
        1. If |config| is failure, [=continue=].
        1. <dfn>Fetch accounts step</dfn>: Let |accountsList| be the result of
            [=fetch the accounts=] with |config|, |provider|, and |globalObject|.
        1. If |accountsList| is failure, or the size of |accountsList| is 0:
            1. [=Set the login status=] of |providerOrigin| to [=logged-out=].
                A user agent may decide to skip this step if no credentials were
                sent to server.

                Note: For example, if the fetch failed due to a DNS error, no
                    credentials were sent and therefore the [=IDP=] did not learn
                    the user's identity. In this situation, we do not know whether
                    the user is signed in or not and so we may not want to reset
                    the status.
            1. If |loginStatus| is [=logged-in=], set |providerMap|[|providerOrigin|] to "mismatch"
                and [=continue=].
        1. Assert: |accountsList| is not failure and the size of |accountsList| is not 0.
        1. [=Set the login status=] for |providerOrigin| to [=logged-in=].
        1. For each |acc| in |accountsList|:
            1. If |acc|["{{IdentityProviderAccount/picture}}"] is present, [=fetch the account picture=]
                with |acc| and |globalObject|. If the [=user agent=] displays this picture to
                the user at any point, it MUST reuse the result of this fetch instead of redownloading
                the picture.

                Note: We require downloading the pictures here before we potentially filter the account
                    list so that the identity provider cannot determine what hints were provided
                    based on which fetches occurred.
        1. If |provider|'s {{IdentityProviderRequestOptions/loginHint}} is not empty:
            1. For every |account| in |accountList|, remove |account| from |accountList| if |account|'s
                {{IdentityProviderAccount/login_hints}} does not [=list/contain=] |provider|'s
                {{IdentityProviderRequestOptions/loginHint}}.
            1. If |accountList| is now empty, set |providerMap|[|providerOrigin|] to "mismatch" and
                continue.
        1. If |provider|'s {{IdentityProviderRequestOptions/domainHint}} is not empty:
            1. For every |account| in |accountList|:
                1. If {{IdentityProviderRequestOptions/domainHint}} is "any":
                    1. If |account|'s {{IdentityProviderAccount/domain_hints}} is empty, remove
                        |account| from |accountList|.
                1. Otherwise, remove |account| from |accountList| if |account|'s
                    {{IdentityProviderAccount/domain_hints}} does not [=list/contain=] |provider|'s
                    {{IdentityProviderRequestOptions/domainHint}}.
            1. If |accountList| is now empty, set |providerMap|[|providerOrigin|] to "mismatch" and
                continue.
        1. If |config|.{{IdentityProviderAPIConfig/account_label}} is present:
            1. For every |account| in |accountList|, remove |account| from |accountList| if |account|'s
                {{IdentityProviderAccount/label_hints}} does not [=list/contain=]
                |config|.{{IdentityProviderAPIConfig/account_label}}.
            1. If |accountList| is now empty, set |providerMap|[|providerOrigin|] to "mismatch" and
                continue.
        1. Set |providerMap|[|providerOrigin|] to |accountsList|.
    1. If |providerMap| [=map/is empty=], return (failure, false).
    1. Let |registeredAccount| and |numRegisteredAccounts| be null and 0, respectively.
    1. Let |selectedAccount| be null.
    1. For each (|providerOrigin|, |value|) in |providerMap|:
        1. If |value| is not a [=list=] |accountsList|, [=continue=].
        1. For each |acc| in |accountsList|:
            1. If |acc| is [=eligible for auto reauthentication=] given the relevant |provider|, and
                |globalObject|, set |registeredAccount| to |acc|, increase |numRegisteredAccounts| by 1,
                and set |requiresUserMediation| be |providerOrigin|'s [=requires user mediation=].
    1. If |mediation| is not "{{CredentialMediationRequirement/required}}", |requiresUserMediation|
        is false, |numRegisteredAccounts| is equal to 1, and |providerMap|'s [=map/values=] do not
        [=map/contain=] "mismatch":
        1. Set |selectedAccount| to |registeredAccount| and |permission| to true. When doing this, the user
            agent MAY show some UI to the user indicating that they are being
            <dfn>auto-reauthenticated</dfn>.
        1. Set |isAutoSelected| to true.
    1. Otherwise, if |mediation| is "{{CredentialMediationRequirement/silent}}" and |providerMap|'s
        [=map/values=] do not [=map/contain=] "mismatch", return (failure, true).
    1. Let |permission|, |permissionRequested|, and |isAutoSelected| be set to false.
    1. Let |allAccounts| be an empty [=list=].
    1. Build UI by adding the following for each (|providerOrigin|, |value|) in |providerMap|:
        1. If |value| is "logged-out", the user agent adds one of the following:
            * Nothing: no UI is shown regarding this [=IDP=].
            * Prompt to continue with this [=IDP=]. If the user continues, the user
                agent SHOULD set the login status to [=unknown=]. This MAY include an
            * Return (failure, false).
            * Prompt the user whether to continue. If the user continues, the user
                agent SHOULD set |loginStatus| to [=unknown=]. This MAY include an
                affordance to [=show an IDP login dialog=].
                * If the user triggers this affordance:
                    1. Let |result| be the result of running
                        [=fetch the config file and show an IDP login dialog=]
                        with the relevant |provider| and |globalObject|.
                    1. If |result| is failure, return (failure, true).
        1. Otherwise, if |value| is "mismatch", add contents indicating this |providerOrigin|
            to the user. The contents SHOULD provide an affordance for the user to trigger
            the [=show an IDP login dialog=] algorithm with the relevant |config| and |provider|;
            this dialog is the <dfn>confirm IDP login dialog</dfn>.

            Note: This situation happens when the browser expects the user
                to be signed in, but the accounts fetch indicated that the user
                is signed out.

            Note: This dialog ensures that silent tracking of the user is
                impossible by always showing UI of some kind when credentials
                were sent to the server.

            * If the [=show an IDP login dialog=] algorithm was triggered:

                1. Let |result| be the result of that algorithm.
                1. If |result| is failure, return (failure, true). The user
                    agent MAY show a dialog to the user before or after
                    returning failure indicating this failure.
                1. Otherwise, go back to the [=fetch accounts step=] to get an updated
                    value of |providerMap| for this [=IDP=].
        1. Otherwise, |value| is a [=list=] of accounts. [=list/Extend=] |allAccounts| with |value|.
    1. Also include a UI affordance to close the dialog. If the user closes this dialog, return (failure,
        true).
    1. <dfn for="create identity credential">Show accounts</dfn> step: if |allAccounts| is not [=list/empty=], also add UI to present the account options to the user.
        If the user selects an account, perform the following steps:
            1. Set |selectedAccount| to the chosen {{IdentityProviderAccount}}.
            1. Close the dialog.
    1. If the [=user agent=] created any dialogs requesting user choice or permission in the previous
        steps, wait until they are closed.
    1. If |permission| is false, then return (failure, true).
    1. Assert: |selectedAccount| is not null.
    1. Let |credential| be the result of running the [=fetch an identity assertion=] algorithm with
        |selectedAccount|'s {{IdentityProviderAccount/id}}, |permissionRequested|, |isAutoSelected|,
        |provider|, |config|, and |globalObject|.
    1. Return |credential|.
</div>

<div class="issue" heading="extension">
An extension may use the following instead of the [=create identity credential/show accounts=] step, where
    |permissionRequested| is sometimes set:
    1. If |allAccounts| is not [=list/empty=], also add UI to present the account options to the user as follows:
        1. If |allAccounts|'s size is 1 and <var ignore="">providerMap</var>'s [=map/values=] do not [=map/contain=]
            "mismatch":
            1. Set |selectedAccount| to |allAccounts|[0].
            1. If [=compute the connection status=] of |selectedAccount|, the relevant |provider|,
                and |globalObject| returns [=compute the connection status/connected=], show a
                dialog to request user permission to sign in via |selectedAccount|, and set the
                result in |permission|. The user agent MAY use |options|'s
                {{IdentityCredentialRequestOptions/context}} and |options|'s
                {{IdentityCredentialRequestOptions/mode}} to customize the dialog.
            1. Otherwise, set |permission| to the result of running [=request permission to sign-up=]
                algorithm with |selectedAccount|, the relevant |config|, the relevant |provider|,
                and |globalObject|. Also set |permissionRequested| to true if the user agent
                [=supports showing a permission prompt=].
        1. Otherwise:
            1. Show UI to allow the user to select an account chooser displaying the options from
                <var ignore="">accountsList</var>.
            1. If the user selects an account, perform the following steps:
                1. Set |selectedAccount| to the chosen {{IdentityProviderAccount}}.
                1. If [=compute the connection status=] of |selectedAccount|, the relevant |provider|,
                    and |globalObject| is [=compute the connection status/connected=], set |permission|
                    to true.
                1. Otherwise, if |provider|.{{IdentityProviderRequestOptions/fields}} is [=list/empty=],
                    [=create a connection between the RP and the IdP account=] with |provider|, |account|,
                    and |globalObject|, and set |permission| to true.
                    Note: The connection would normally be created in the [=request permission to sign-up=]
                        algorithm, but we do not want to show an extra dialog in this case.
                1. Otherwise:
                    1. Set |permission| to the result of running the [=request permission to sign-up=]
                        algorithm with |selectedAccount|, the relevant |config|, the relevant |provider|,
                        and |globalObject|.
                    1. Set |permissionRequested| to true.
</div>


<!-- ============================================================ -->
### Fetch the config file ### {#fetch-config-file}
<!-- ============================================================ -->

The <a>fetch the config file</a> algorithm fetches both the [=well-known file=] and the config file from
the [=IDP=], checks that the config file is mentioned in the [=well-known file=], and returns the config.

<div algorithm>
To <dfn>fetch the config file</dfn> given an {{IdentityProviderRequestOptions}} |provider| and
|globalObject|, run the following steps. This returns an {{IdentityProviderAPIConfig}}
or failure.
    1. Let |configUrl| be the result of running [=parse url=] with |provider|'s
        {{IdentityProviderConfig/configURL}} and |globalObject|.
    1. If |configUrl| is failure, return failure.
    1. Run a [[!CSP]] check with a [[CSP#directive-connect-src|connect-src]] directive on the URL
        passed as |configUrl|. If it fails, return failure.
    1. If |configUrl| is not a [=potentially trustworthy URL=], return failure.
    1. Let |rootUrl| be a new [=/URL=].
    1. Set |rootUrl|'s [=url/scheme=] to |configUrl|'s [=url/scheme=].
    1. Set |rootUrl|'s [=url/host=] to |configUrl|'s [=url/host=]'s [=host/registrable domain=].
    1. Set |rootUrl|'s [=url/path=] to the <a>list</a> «".well-known", "web-identity"».
    1. Let |config|, |wellKnown|, |accounts_url|, and |login_url| be null.
    1. Let |skipWellKnown| be false.
    1. Let |rpOrigin| be |globalObject|'s [=associated Document=]'s [=Document/origin=].
    1. If |rpOrigin| is not an [=opaque origin=], and |rootUrl|'s [=url/host=] is equal
        to |rpOrigin|'s [=host/registrable domain=], and |rootUrl|'s [=url/scheme=] is
        equal to |rpOrigin|'s [=origin/scheme=], set |skipWellKnown| to true.

        Note: Because domain cookies are valid across an entire site, there is no privacy
            benefit from doing the well-known check if the RP and IDP are in the same site.
    1. Otherwise:
        1. Let |wellKnownRequest| be a new [=/request=] as follows:

            :  [=request/URL=]
            :: |rootUrl|
            :  [=request/client=]
            :: null
            :  [=request/window=]
            :: "no-window"
            :  [=request/service-workers mode=]
            :: "none"
            :  [=request/destination=]
            :: "webidentity"
            :  [=request/origin=]
            :: a unique [=opaque origin=]
            :  [=request/header list=]
            :: a [=list=] containing a single [=header=] with [=header/name=] set to `Accept` and
                [=header/value=] set to `application/json`
            :  [=request/referrer policy=]
            :: "no-referrer"
            :  [=request/credentials mode=]
            :: "omit"
            :  [=request/mode=]
            :: "no-cors"

            Issue: The spec is yet to be updated so that all <a spec=fetch for=/>requests</a> are created
            with [=request/mode=] set to "user-agent-no-cors". See the relevant
            [pull request](https://github.com/whatwg/fetch/pull/1533) for details.

        1. [=Fetch request=] with |wellKnownRequest| and |globalObject|, and with <var ignore>processResponseConsumeBody</var>
            set to the following steps, given a <a spec=fetch for=/>response</a> |response| and |responseBody|:
            1. Let |json| be the result of [=extract the JSON fetch response=] from |response| and
                |responseBody|.
            1. Set |wellKnown| to the result of [=converted to an IDL value|converting=] |json|
                to an {{IdentityProviderWellKnown}}.
            1. If one of the previous two steps threw an exception, or if the
                [=list/size=] of |wellKnown|["{{IdentityProviderWellKnown/provider_urls}}"] is
                greater than 1, set |wellKnown| to failure.

                Issue: [relax](https://github.com/fedidcg/FedCM/issues/333) the size of the
                provider_urls array.

    1. Let |configRequest| be a new <a spec=fetch for=/>request</a> as follows:

        :  [=request/url=]
        :: |configUrl|
        :  [=request/redirect mode=]
        :: "error"
        :  [=request/client=]
        :: null
        :  [=request/window=]
        :: "no-window"
        :  [=request/service-workers mode=]
        :: "none"
        :  [=request/destination=]
        :: "webidentity"
        :  [=request/origin=]
        :: a unique [=opaque origin=]
        :  [=request/header list=]
        :: a [=list=] containing a single [=header=] with [=header/name=] set to `Accept` and
            [=header/value=] set to `application/json`
        :  [=request/referrer policy=]
        :: "no-referrer"
        :  [=request/credentials mode=]
        :: "omit"
        :  [=request/mode=]
        :: "no-cors"

        Issue: The spec is yet to be updated so that all <a spec=fetch for=/>requests</a> are created
        with [=request/mode=] set to "user-agent-no-cors". See the relevant
        [pull request](https://github.com/whatwg/fetch/pull/1533) for details.

    1. [=Fetch request=] with |configRequest| and |globalObject|, and with <var ignore>processResponseConsumeBody</var>
        set to the following steps given a <a spec=fetch for=/>response</a> |response| and |responseBody|:
        1. Let |json| be the result of [=extract the JSON fetch response=] from |response| and
            |responseBody|.
        1. [=converted to an IDL value|Convert=] |json| to an {{IdentityProviderAPIConfig}} stored
            in |config|.
        1. If one of the previous two steps threw an exception, set |config| to failure.
        1. Set |login_url| to the result of [=computing the manifest URL=] with |provider|,
            |config|.{{IdentityProviderAPIConfig/login_url}}, and |globalObject|.
        1. Set |accounts_url| to the result of [=computing the manifest URL=] with |provider|,
            |config|.{{IdentityProviderAPIConfig/accounts_endpoint}}, and |globalObject|.
        1. If |login_url| or |accounts_url| is failure, set |config| to failure.
    1. Wait for |config| to be set.
    1. If |config| is failure, return failure.
    1. If |skipWellKnown| is true, return |config|.
    1. Wait for |wellKnown| to be set.
    1. If |wellKnown| is failure, return failure.
    1. If |wellKnown|.{{IdentityProviderWellKnown/accounts_endpoint}} and
        |wellKnown|.{{IdentityProviderWellKnown/login_url}} are set:
        1. Let |well_known_accounts_url| be the result of [=computing the manifest URL=] with
            |provider|, |wellKnown|.{{IdentityProviderWellKnown/accounts_endpoint}},
            and |globalObject|.
        1. Let |well_known_login_url| be the result of [=computing the manifest URL=] with |provider|,
            |wellKnown|.{{IdentityProviderWellKnown/login_url}}, and |globalObject|.
        1. If |well_known_accounts_url| is not [=url/equal=] to |accounts_url|, return failure.
        1. If |well_known_login_url| is not [=url/equal=] to |login_url|, return failure.
    1. Otherwise:
        1. Let |allowed_config_url| be the result of [=computing the manifest URL=] with |provider|,
            |wellKnown|.{{IdentityProviderWellKnown/provider_urls}}[0], and |globalObject|.
        1. If |allowed_config_url| is not [=url/equal=] to |configUrl|, return failure.
    1. Return |config|.

</div>

NOTE: a two-tier file system is used in order to prevent the [=IDP=] from easily determining the [=RP=]
that a user is visiting by encoding the information in the config file path. This issue is solved by
requiring a [=well-known file=] to be on the root of the [=IDP=]. The config file itself can be anywhere, but
it will not be used if the user agent does not find it in the [=well-known file=]. This allows the [=IDP=]
to keep their actual config files on an arbitary path while allowing the user agent to prevent config file
path manipulation to fingerprint (for instance, by including the RP in the path). See
[[#manifest-fingerprinting]].

<xmp class="idl">
dictionary IdentityProviderWellKnown {
  sequence<USVString> provider_urls;
  USVString accounts_endpoint;
  USVString login_url;
};

dictionary IdentityProviderIcon {
  required USVString url;
  unsigned long size;
};

dictionary IdentityProviderBranding {
  USVString background_color;
  USVString color;
  sequence<IdentityProviderIcon> icons;
  USVString name;
};

dictionary IdentityProviderAPIConfig {
  required USVString accounts_endpoint;
  required USVString client_metadata_endpoint;
  required USVString id_assertion_endpoint;
  required USVString login_url;
  USVString disconnect_endpoint;
  IdentityProviderBranding branding;
  USVString account_label;
};
</xmp>

<!-- ============================================================ -->
### Fetch the accounts ### {#fetch-accounts}
<!-- ============================================================ -->

The <a>fetch the accounts</a> algorithm fetches the […
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

6 participants