├── .dockerignore
├── .editorconfig
├── .github
├── CODEOWNERS
├── FUNDING.yml
├── dependabot.yml
└── workflows
│ ├── api-breakage.yml
│ ├── ci.yml
│ ├── nightly.yml
│ ├── validate.yml
│ └── verify-documentation.yml
├── .gitignore
├── .spi.yml
├── .swift-format
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── Package.swift
├── README.md
├── Sources
├── CBcrypt
│ ├── bcrypt.c
│ ├── blf.c
│ ├── blf.h
│ └── include
│ │ └── bcrypt.h
├── HummingbirdAuth
│ ├── Authenticator
│ │ ├── AuthRequestContext.swift
│ │ ├── Authenticator.swift
│ │ └── ClosureAuthenticator.swift
│ ├── BasicAuthentication.swift
│ ├── BearerAuthentication.swift
│ ├── Deprecated.swift
│ ├── Middleware
│ │ └── IsAuthenticatedMiddleware.swift
│ └── Sessions
│ │ ├── SessionAuthenticator.swift
│ │ ├── SessionContext.swift
│ │ ├── SessionMiddleware.swift
│ │ ├── SessionStorage.swift
│ │ └── UserSessionRepository.swift
├── HummingbirdAuthTesting
│ └── TestClient+Auth.swift
├── HummingbirdBasicAuth
│ ├── BasicAuthenticator.swift
│ ├── PasswordVerifier.swift
│ └── UserPasswordRepository.swift
├── HummingbirdBcrypt
│ └── Bcrypt.swift
└── HummingbirdOTP
│ └── OTP.swift
├── Tests
└── HummingbirdAuthTests
│ ├── AuthTests.swift
│ ├── BcryptTests.swift
│ ├── OTPTests.swift
│ └── SessionTests.swift
└── scripts
└── validate.sh
/.dockerignore:
--------------------------------------------------------------------------------
1 | .build
2 | .git
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | indent_style = space
5 | indent_size = 4
6 | end_of_line = lf
7 | insert_final_newline = true
8 | trim_trailing_whitespace = true
--------------------------------------------------------------------------------
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | * @adam-fowler @Joannis
2 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: adam-fowler
2 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: "github-actions"
4 | directory: "/"
5 | schedule:
6 | interval: "daily"
7 | ignore:
8 | - dependency-name: "codecov/codecov-action"
9 | update-types: ["version-update:semver-major"]
10 | groups:
11 | dependencies:
12 | patterns:
13 | - "*"
14 | - package-ecosystem: "swift"
15 | directory: "/"
16 | schedule:
17 | interval: "daily"
18 | open-pull-requests-limit: 5
19 | allow:
20 | - dependency-type: all
21 | groups:
22 | all-dependencies:
23 | patterns:
24 | - "*"
25 |
--------------------------------------------------------------------------------
/.github/workflows/api-breakage.yml:
--------------------------------------------------------------------------------
1 | name: API breaking changes
2 |
3 | on:
4 | pull_request:
5 | concurrency:
6 | group: ${{ github.workflow }}-${{ github.ref }}-apibreakage
7 | cancel-in-progress: true
8 |
9 | jobs:
10 | linux:
11 | runs-on: ubuntu-latest
12 | timeout-minutes: 15
13 | container:
14 | image: swift:latest
15 | steps:
16 | - name: Checkout
17 | uses: actions/checkout@v4
18 | with:
19 | fetch-depth: 0
20 | # https://github.com/actions/checkout/issues/766
21 | - name: Mark the workspace as safe
22 | run: git config --global --add safe.directory ${GITHUB_WORKSPACE}
23 | - name: API breaking changes
24 | run: |
25 | swift package diagnose-api-breaking-changes origin/${GITHUB_BASE_REF}
26 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | paths:
8 | - '**.swift'
9 | - '**.yml'
10 | pull_request:
11 | workflow_dispatch:
12 | concurrency:
13 | group: ${{ github.workflow }}-${{ github.ref }}-ci
14 | cancel-in-progress: true
15 |
16 | jobs:
17 | linux:
18 | runs-on: ubuntu-latest
19 | timeout-minutes: 15
20 | strategy:
21 | matrix:
22 | image: ["swift:5.10", "swift:6.0", "swift:6.1"]
23 | container:
24 | image: ${{ matrix.image }}
25 | steps:
26 | - name: Checkout
27 | uses: actions/checkout@v4
28 | - name: Test
29 | run: |
30 | swift test --enable-code-coverage
31 | - name: Convert coverage files
32 | run: |
33 | llvm-cov export -format="lcov" \
34 | .build/debug/hummingbird-authPackageTests.xctest \
35 | -ignore-filename-regex="\/Tests\/" \
36 | -ignore-filename-regex="\/Benchmarks\/" \
37 | -instr-profile .build/debug/codecov/default.profdata > info.lcov
38 | - name: Upload to codecov.io
39 | uses: codecov/codecov-action@v4
40 | with:
41 | files: info.lcov
42 | token: ${{ secrets.CODECOV_TOKEN }}
43 |
--------------------------------------------------------------------------------
/.github/workflows/nightly.yml:
--------------------------------------------------------------------------------
1 | name: Swift nightly build
2 |
3 | on:
4 | workflow_dispatch:
5 |
6 | jobs:
7 | linux:
8 | runs-on: ubuntu-latest
9 | timeout-minutes: 15
10 | strategy:
11 | matrix:
12 | image: ['nightly-focal', 'nightly-jammy', 'nightly-amazonlinux2']
13 | container:
14 | image: swiftlang/swift:${{ matrix.image }}
15 | steps:
16 | - name: Checkout
17 | uses: actions/checkout@v4
18 | - name: Test
19 | run: |
20 | swift test
21 |
--------------------------------------------------------------------------------
/.github/workflows/validate.yml:
--------------------------------------------------------------------------------
1 | name: Validity Check
2 |
3 | on:
4 | pull_request:
5 | concurrency:
6 | group: ${{ github.workflow }}-${{ github.ref }}-validate
7 | cancel-in-progress: true
8 |
9 | jobs:
10 | validate:
11 | runs-on: ubuntu-latest
12 | timeout-minutes: 15
13 | steps:
14 | - name: Checkout
15 | uses: actions/checkout@v4
16 | with:
17 | fetch-depth: 1
18 | - name: run script
19 | run: ./scripts/validate.sh
20 |
--------------------------------------------------------------------------------
/.github/workflows/verify-documentation.yml:
--------------------------------------------------------------------------------
1 | name: Verify Documentation
2 |
3 | on:
4 | pull_request:
5 | concurrency:
6 | group: ${{ github.workflow }}-${{ github.ref }}-verifydocs
7 | cancel-in-progress: true
8 |
9 | jobs:
10 | linux:
11 | runs-on: ubuntu-latest
12 | timeout-minutes: 15
13 | container:
14 | image: swift:latest
15 | steps:
16 | - name: Install rsync 📚
17 | run: |
18 | apt-get update && apt-get install -y rsync bc
19 | - name: Checkout
20 | uses: actions/checkout@v4
21 | with:
22 | fetch-depth: 0
23 | path: "package"
24 | - name: Checkout
25 | uses: actions/checkout@v4
26 | with:
27 | repository: "hummingbird-project/hummingbird-docs"
28 | fetch-depth: 0
29 | path: "documentation"
30 | - name: Verify
31 | run: |
32 | cd documentation
33 | swift package edit ${GITHUB_REPOSITORY#*/} --path ../package
34 | ./scripts/build-docc.sh -e
35 |
36 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | .build/
3 | .swiftpm/
4 | .vscode/
5 | .index-build/
6 | .devcontainer/
7 | /Packages
8 | /*.xcodeproj
9 | xcuserdata/
10 | Package.resolved
11 | /public
12 | /docs
13 | .benchmarkBaselines
--------------------------------------------------------------------------------
/.spi.yml:
--------------------------------------------------------------------------------
1 | version: 1
2 | external_links:
3 | documentation: "https://docs.hummingbird.codes/2.0/documentation/hummingbirdauth"
--------------------------------------------------------------------------------
/.swift-format:
--------------------------------------------------------------------------------
1 | {
2 | "version" : 1,
3 | "indentation" : {
4 | "spaces" : 4
5 | },
6 | "tabWidth" : 4,
7 | "fileScopedDeclarationPrivacy" : {
8 | "accessLevel" : "private"
9 | },
10 | "spacesAroundRangeFormationOperators" : false,
11 | "indentConditionalCompilationBlocks" : false,
12 | "indentSwitchCaseLabels" : false,
13 | "lineBreakAroundMultilineExpressionChainComponents" : false,
14 | "lineBreakBeforeControlFlowKeywords" : false,
15 | "lineBreakBeforeEachArgument" : true,
16 | "lineBreakBeforeEachGenericRequirement" : true,
17 | "lineLength" : 150,
18 | "maximumBlankLines" : 1,
19 | "respectsExistingLineBreaks" : true,
20 | "prioritizeKeepingFunctionOutputTogether" : true,
21 | "multiElementCollectionTrailingCommas" : true,
22 | "rules" : {
23 | "AllPublicDeclarationsHaveDocumentation" : false,
24 | "AlwaysUseLiteralForEmptyCollectionInit" : false,
25 | "AlwaysUseLowerCamelCase" : false,
26 | "AmbiguousTrailingClosureOverload" : true,
27 | "BeginDocumentationCommentWithOneLineSummary" : false,
28 | "DoNotUseSemicolons" : true,
29 | "DontRepeatTypeInStaticProperties" : true,
30 | "FileScopedDeclarationPrivacy" : true,
31 | "FullyIndirectEnum" : true,
32 | "GroupNumericLiterals" : true,
33 | "IdentifiersMustBeASCII" : true,
34 | "NeverForceUnwrap" : false,
35 | "NeverUseForceTry" : false,
36 | "NeverUseImplicitlyUnwrappedOptionals" : false,
37 | "NoAccessLevelOnExtensionDeclaration" : true,
38 | "NoAssignmentInExpressions" : true,
39 | "NoBlockComments" : true,
40 | "NoCasesWithOnlyFallthrough" : true,
41 | "NoEmptyTrailingClosureParentheses" : true,
42 | "NoLabelsInCasePatterns" : true,
43 | "NoLeadingUnderscores" : false,
44 | "NoParensAroundConditions" : true,
45 | "NoVoidReturnOnFunctionSignature" : true,
46 | "OmitExplicitReturns" : true,
47 | "OneCasePerLine" : true,
48 | "OneVariableDeclarationPerLine" : true,
49 | "OnlyOneTrailingClosureArgument" : true,
50 | "OrderedImports" : true,
51 | "ReplaceForEachWithForLoop" : true,
52 | "ReturnVoidInsteadOfEmptyTuple" : true,
53 | "UseEarlyExits" : false,
54 | "UseExplicitNilCheckInConditions" : false,
55 | "UseLetInEveryBoundCaseVariable" : false,
56 | "UseShorthandTypeNames" : true,
57 | "UseSingleLinePropertyGetter" : false,
58 | "UseSynthesizedInitializer" : false,
59 | "UseTripleSlashForDocumentationComments" : true,
60 | "UseWhereClausesInForLoops" : false,
61 | "ValidateDocumentationComments" : false
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Code of Conduct
2 |
3 | All developers should feel welcome and encouraged to contribute to Hummingbird. Because of this we have adopted the code of conduct defined by [contributor-covenant.org](https://www.contributor-covenant.org). This document is used across many open source
4 | communities, and we think it articulates our values well. The full text is copied below:
5 |
6 | ## Contributor Code of Conduct v1.3
7 |
8 | As contributors and maintainers of this project, and in the interest of
9 | fostering an open and welcoming community, we pledge to respect all people who
10 | contribute through reporting issues, posting feature requests, updating
11 | documentation, submitting pull requests or patches, and other activities.
12 |
13 | We are committed to making participation in this project a harassment-free
14 | experience for everyone, regardless of level of experience, gender, gender
15 | identity and expression, sexual orientation, disability, personal appearance,
16 | body size, race, ethnicity, age, religion, or nationality.
17 |
18 | Examples of unacceptable behavior by participants include:
19 |
20 | * The use of sexualized language or imagery
21 | * Personal attacks
22 | * Trolling or insulting/derogatory comments
23 | * Public or private harassment
24 | * Publishing other's private information, such as physical or electronic
25 | addresses, without explicit permission
26 | * Other unethical or unprofessional conduct
27 |
28 | Project maintainers have the right and responsibility to remove, edit, or
29 | reject comments, commits, code, wiki edits, issues, and other contributions
30 | that are not aligned to this Code of Conduct, or to ban temporarily or
31 | permanently any contributor for other behaviors that they deem inappropriate,
32 | threatening, offensive, or harmful.
33 |
34 | By adopting this Code of Conduct, project maintainers commit themselves to
35 | fairly and consistently applying these principles to every aspect of managing
36 | this project. Project maintainers who do not follow or enforce the Code of
37 | Conduct may be permanently removed from the project team.
38 |
39 | This Code of Conduct applies both within project spaces and in public spaces
40 | when an individual is representing the project or its community.
41 |
42 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
43 | reported by contacting a project maintainer at [INSERT EMAIL ADDRESS]. All
44 | complaints will be reviewed and investigated and will result in a response that
45 | is deemed necessary and appropriate to the circumstances. Maintainers are
46 | obligated to maintain confidentiality with regard to the reporter of an
47 | incident.
48 |
49 |
50 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
51 | version 1.3.0, available at https://www.contributor-covenant.org/version/1/3/0/code-of-conduct.html
52 |
53 | [homepage]: https://www.contributor-covenant.org
54 |
55 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | ## Legal
4 | By submitting a pull request, you represent that you have the right to license your contribution to the community, and agree by submitting the patch
5 | that your contributions are licensed under the Apache 2.0 license (see [LICENSE](LICENSE)).
6 |
7 | ## Contributor Conduct
8 | All contributors are expected to adhere to the project's [Code of Conduct](CODE_OF_CONDUCT.md).
9 |
10 | ## Submitting a bug or issue
11 | Please ensure to include the following in your bug report
12 | - A consise description of the issue, what happened and what you expected.
13 | - Simple reproduction steps
14 | - Version of the library you are using
15 | - Contextual information (Swift version, OS etc)
16 |
17 | ## Submitting a Pull Request
18 |
19 | Please ensure to include the following in your Pull Request
20 | - A description of what you are trying to do. What the PR provides to the library, additional functionality, fixing a bug etc
21 | - A description of the code changes
22 | - Documentation on how these changes are being tested
23 | - Additional tests to show your code working and to ensure future changes don't break your code.
24 |
25 | Please keep your PRs to a minimal number of changes. If a PR is large try to split it up into smaller PRs. Don't move code around unnecessarily it makes comparing old with new very hard.
26 |
27 | The main development branch of the repository is `main`.
28 |
29 | ### Formatting
30 |
31 | We use Apple's swift-format for formatting code. PRs will not be accepted if they haven't be formatted.
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | # ================================
2 | # Build image
3 | # ================================
4 | FROM swift:6.0 as build
5 |
6 | WORKDIR /build
7 |
8 | # First just resolve dependencies.
9 | # This creates a cached layer that can be reused
10 | # as long as your Package.swift/Package.resolved
11 | # files do not change.
12 | COPY ./Package.* ./
13 | RUN swift package resolve
14 |
15 | # Copy entire repo into container
16 | COPY . .
17 |
18 | RUN swift test --sanitize=thread
19 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2021 Adam Fowler
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/Package.swift:
--------------------------------------------------------------------------------
1 | // swift-tools-version:5.9
2 | // The swift-tools-version declares the minimum version of Swift required to build this package.
3 |
4 | import PackageDescription
5 |
6 | let package = Package(
7 | name: "hummingbird-auth",
8 | platforms: [.macOS(.v14), .iOS(.v17), .tvOS(.v17)],
9 | products: [
10 | .library(name: "HummingbirdAuth", targets: ["HummingbirdAuth"]),
11 | .library(name: "HummingbirdBasicAuth", targets: ["HummingbirdBasicAuth"]),
12 | .library(name: "HummingbirdBcrypt", targets: ["HummingbirdBcrypt"]),
13 | .library(name: "HummingbirdOTP", targets: ["HummingbirdOTP"]),
14 | .library(name: "HummingbirdAuthTesting", targets: ["HummingbirdAuthTesting"]),
15 | ],
16 | dependencies: [
17 | .package(url: "https://github.com/hummingbird-project/hummingbird.git", from: "2.5.0"),
18 | .package(url: "https://github.com/apple/swift-crypto.git", "1.0.0"..<"5.0.0"),
19 | .package(url: "https://github.com/apple/swift-nio.git", from: "2.63.0"),
20 | .package(url: "https://github.com/swift-extras/swift-extras-base64.git", from: "1.0.0"),
21 | ],
22 | targets: [
23 | .target(
24 | name: "HummingbirdAuth",
25 | dependencies: [
26 | .product(name: "Hummingbird", package: "hummingbird"),
27 | .product(name: "ExtrasBase64", package: "swift-extras-base64"),
28 | ]
29 | ),
30 | .target(
31 | name: "HummingbirdBasicAuth",
32 | dependencies: [
33 | .byName(name: "HummingbirdAuth"),
34 | .byName(name: "HummingbirdBcrypt"),
35 | .product(name: "Hummingbird", package: "hummingbird"),
36 | ]
37 | ),
38 | .target(
39 | name: "HummingbirdBcrypt",
40 | dependencies: [
41 | .byName(name: "CBcrypt")
42 | ]
43 | ),
44 | .target(
45 | name: "HummingbirdOTP",
46 | dependencies: [
47 | .product(name: "Crypto", package: "swift-crypto"),
48 | .product(name: "ExtrasBase64", package: "swift-extras-base64"),
49 | ]
50 | ),
51 | .target(
52 | name: "HummingbirdAuthTesting",
53 | dependencies: [
54 | .byName(name: "HummingbirdAuth"),
55 | .product(name: "HummingbirdTesting", package: "hummingbird"),
56 | ]
57 | ),
58 | .target(name: "CBcrypt", dependencies: []),
59 | .testTarget(
60 | name: "HummingbirdAuthTests",
61 | dependencies: [
62 | .byName(name: "HummingbirdAuth"),
63 | .byName(name: "HummingbirdBasicAuth"),
64 | .byName(name: "HummingbirdBcrypt"),
65 | .byName(name: "HummingbirdOTP"),
66 | .byName(name: "HummingbirdAuthTesting"),
67 | .product(name: "HummingbirdTesting", package: "hummingbird"),
68 | .product(name: "NIOPosix", package: "swift-nio"),
69 | ]
70 | ),
71 | ]
72 | )
73 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | # Hummingbird Auth
20 |
21 | Authentication framework and extensions for Hummingbird server framework.
22 |
23 | Includes authentication and session middleware, bearer, basic authentication extraction from your Request headers, Bcrypt encryption for passwords.
24 |
25 |
26 | ## Documentation
27 |
28 | You can find documentation for HummingbirdAuth [here](https://docs.hummingbird.codes/2.0/documentation/hummingbirdauth). The [hummingbird-examples](https://github.com/hummingbird-project/hummingbird-examples) repository has a number of examples of different uses of the library.
29 |
--------------------------------------------------------------------------------
/Sources/CBcrypt/bcrypt.c:
--------------------------------------------------------------------------------
1 | /* $OpenBSD: bcrypt.c,v 1.58 2020/07/06 13:33:05 pirofti Exp $ */
2 |
3 | /*
4 | * Copyright (c) 2014 Ted Unangst
5 | * Copyright (c) 1997 Niels Provos
6 | *
7 | * Permission to use, copy, modify, and distribute this software for any
8 | * purpose with or without fee is hereby granted, provided that the above
9 | * copyright notice and this permission notice appear in all copies.
10 | *
11 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 | */
19 | /* This password hashing algorithm was designed by David Mazieres
20 | * and works as follows:
21 | *
22 | * 1. state := InitState ()
23 | * 2. state := ExpandKey (state, salt, password)
24 | * 3. REPEAT rounds:
25 | * state := ExpandKey (state, 0, password)
26 | * state := ExpandKey (state, 0, salt)
27 | * 4. ctext := "OrpheanBeholderScryDoubt"
28 | * 5. REPEAT 64:
29 | * ctext := Encrypt_ECB (state, ctext);
30 | * 6. RETURN Concatenate (salt, ctext);
31 | *
32 | */
33 |
34 | #include
35 | #include
36 | #include
37 | #include
38 | #include
39 | #include
40 | #include
41 | #include
42 | #include "blf.h"
43 | #include "bcrypt.h"
44 |
45 | /* This implementation is adaptable to current computing power.
46 | * You can have up to 2^31 rounds which should be enough for some
47 | * time to come.
48 | */
49 | // timingsafe_bcmp is unavailable so use memcmp
50 | #define timingsafe_bcmp memcmp
51 |
52 | static int encode_base64(char *, const u_int8_t *, size_t);
53 | static int decode_base64(u_int8_t *, size_t, const char *);
54 |
55 | #define explicit_bzero(s,n) memset(s, 0, n)
56 | #define DEF_WEAK(f)
57 |
58 | /*
59 | * Generates a salt for this version of crypt.
60 | */
61 | int
62 | c_hb_bcrypt_initsalt_with_csalt(int log_rounds, char *salt, size_t saltbuflen, const uint8_t *csalt)
63 | {
64 | if (saltbuflen < BCRYPT_SALTSPACE) {
65 | errno = EINVAL;
66 | return -1;
67 | }
68 |
69 | if (log_rounds < 4)
70 | log_rounds = 4;
71 | else if (log_rounds > 31)
72 | log_rounds = 31;
73 |
74 | snprintf(salt, saltbuflen, "$2b$%2.2u$", log_rounds);
75 | encode_base64(salt + 7, csalt, BCRYPT_MAXSALT);
76 |
77 | return 0;
78 | }
79 |
80 | /*
81 | * the core bcrypt function
82 | */
83 | int
84 | c_hb_bcrypt_hashpass(const char *key, const char *salt, char *encrypted,
85 | size_t encryptedlen)
86 | {
87 | blf_ctx state;
88 | u_int32_t rounds, i, k;
89 | u_int16_t j;
90 | size_t key_len;
91 | u_int8_t salt_len, logr, minor;
92 | u_int8_t ciphertext[4 * BCRYPT_WORDS] = "OrpheanBeholderScryDoubt";
93 | u_int8_t csalt[BCRYPT_MAXSALT];
94 | u_int32_t cdata[BCRYPT_WORDS];
95 |
96 | if (encryptedlen < BCRYPT_HASHSPACE)
97 | goto inval;
98 |
99 | /* Check and discard "$" identifier */
100 | if (salt[0] != '$')
101 | goto inval;
102 | salt += 1;
103 |
104 | if (salt[0] != BCRYPT_VERSION)
105 | goto inval;
106 |
107 | /* Check for minor versions */
108 | switch ((minor = salt[1])) {
109 | case 'a':
110 | key_len = (u_int8_t)(strlen(key) + 1);
111 | break;
112 | case 'b':
113 | /* strlen() returns a size_t, but the function calls
114 | * below result in implicit casts to a narrower integer
115 | * type, so cap key_len at the actual maximum supported
116 | * length here to avoid integer wraparound */
117 | key_len = strlen(key);
118 | if (key_len > 72)
119 | key_len = 72;
120 | key_len++; /* include the NUL */
121 | break;
122 | default:
123 | goto inval;
124 | }
125 | if (salt[2] != '$')
126 | goto inval;
127 | /* Discard version + "$" identifier */
128 | salt += 3;
129 |
130 | /* Check and parse num rounds */
131 | if (!isdigit((unsigned char)salt[0]) ||
132 | !isdigit((unsigned char)salt[1]) || salt[2] != '$')
133 | goto inval;
134 | logr = (salt[1] - '0') + ((salt[0] - '0') * 10);
135 | if (logr < BCRYPT_MINLOGROUNDS || logr > 31)
136 | goto inval;
137 | /* Computer power doesn't increase linearly, 2^x should be fine */
138 | rounds = 1U << logr;
139 |
140 | /* Discard num rounds + "$" identifier */
141 | salt += 3;
142 |
143 | if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT)
144 | goto inval;
145 |
146 | /* We dont want the base64 salt but the raw data */
147 | if (decode_base64(csalt, BCRYPT_MAXSALT, salt))
148 | goto inval;
149 | salt_len = BCRYPT_MAXSALT;
150 |
151 | /* Setting up S-Boxes and Subkeys */
152 | Blowfish_initstate(&state);
153 | Blowfish_expandstate(&state, csalt, salt_len,
154 | (u_int8_t *) key, key_len);
155 | for (k = 0; k < rounds; k++) {
156 | Blowfish_expand0state(&state, (u_int8_t *) key, key_len);
157 | Blowfish_expand0state(&state, csalt, salt_len);
158 | }
159 |
160 | /* This can be precomputed later */
161 | j = 0;
162 | for (i = 0; i < BCRYPT_WORDS; i++)
163 | cdata[i] = Blowfish_stream2word(ciphertext, 4 * BCRYPT_WORDS, &j);
164 |
165 | /* Now do the encryption */
166 | for (k = 0; k < 64; k++)
167 | blf_enc(&state, cdata, BCRYPT_WORDS / 2);
168 |
169 | for (i = 0; i < BCRYPT_WORDS; i++) {
170 | ciphertext[4 * i + 3] = cdata[i] & 0xff;
171 | cdata[i] = cdata[i] >> 8;
172 | ciphertext[4 * i + 2] = cdata[i] & 0xff;
173 | cdata[i] = cdata[i] >> 8;
174 | ciphertext[4 * i + 1] = cdata[i] & 0xff;
175 | cdata[i] = cdata[i] >> 8;
176 | ciphertext[4 * i + 0] = cdata[i] & 0xff;
177 | }
178 |
179 |
180 | snprintf(encrypted, 8, "$2%c$%2.2u$", minor, logr);
181 | encode_base64(encrypted + 7, csalt, BCRYPT_MAXSALT);
182 | encode_base64(encrypted + 7 + 22, ciphertext, 4 * BCRYPT_WORDS - 1);
183 | explicit_bzero(&state, sizeof(state));
184 | explicit_bzero(ciphertext, sizeof(ciphertext));
185 | explicit_bzero(csalt, sizeof(csalt));
186 | explicit_bzero(cdata, sizeof(cdata));
187 | return 0;
188 |
189 | inval:
190 | errno = EINVAL;
191 | return -1;
192 | }
193 |
194 | int
195 | c_hb_bcrypt_checkpass(const char *pass, const char *goodhash)
196 | {
197 | char hash[BCRYPT_HASHSPACE];
198 |
199 | if (c_hb_bcrypt_hashpass(pass, goodhash, hash, sizeof(hash)) != 0)
200 | return -1;
201 | if (strlen(hash) != strlen(goodhash) ||
202 | timingsafe_bcmp(hash, goodhash, strlen(goodhash)) != 0) {
203 | errno = EACCES;
204 | return -1;
205 | }
206 |
207 | explicit_bzero(hash, sizeof(hash));
208 | return 0;
209 | }
210 | DEF_WEAK(bcrypt_checkpass);
211 |
212 | /*
213 | * internal utilities
214 | */
215 | static const u_int8_t Base64Code[] =
216 | "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
217 |
218 | static const u_int8_t index_64[128] = {
219 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
220 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
221 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
222 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
223 | 255, 255, 255, 255, 255, 255, 0, 1, 54, 55,
224 | 56, 57, 58, 59, 60, 61, 62, 63, 255, 255,
225 | 255, 255, 255, 255, 255, 2, 3, 4, 5, 6,
226 | 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
227 | 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
228 | 255, 255, 255, 255, 255, 255, 28, 29, 30,
229 | 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
230 | 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
231 | 51, 52, 53, 255, 255, 255, 255, 255
232 | };
233 | #define CHAR64(c) ( (c) > 127 ? 255 : index_64[(c)])
234 |
235 | /*
236 | * read buflen (after decoding) bytes of data from b64data
237 | */
238 | static int
239 | decode_base64(u_int8_t *buffer, size_t len, const char *b64data)
240 | {
241 | u_int8_t *bp = buffer;
242 | const char *p = b64data;
243 | u_int8_t c1, c2, c3, c4;
244 |
245 | while (bp < buffer + len) {
246 | c1 = CHAR64(*p);
247 | /* Invalid data */
248 | if (c1 == 255)
249 | return -1;
250 |
251 | c2 = CHAR64(*(p + 1));
252 | if (c2 == 255)
253 | return -1;
254 |
255 | *bp++ = (c1 << 2) | ((c2 & 0x30) >> 4);
256 | if (bp >= buffer + len)
257 | break;
258 |
259 | c3 = CHAR64(*(p + 2));
260 | if (c3 == 255)
261 | return -1;
262 |
263 | *bp++ = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2);
264 | if (bp >= buffer + len)
265 | break;
266 |
267 | c4 = CHAR64(*(p + 3));
268 | if (c4 == 255)
269 | return -1;
270 | *bp++ = ((c3 & 0x03) << 6) | c4;
271 |
272 | p += 4;
273 | }
274 | return 0;
275 | }
276 |
277 | /*
278 | * Turn len bytes of data into base64 encoded data.
279 | * This works without = padding.
280 | */
281 | static int
282 | encode_base64(char *b64buffer, const u_int8_t *data, size_t len)
283 | {
284 | char *bp = b64buffer;
285 | const u_int8_t *p = data;
286 | u_int8_t c1, c2;
287 |
288 | while (p < data + len) {
289 | c1 = *p++;
290 | *bp++ = Base64Code[(c1 >> 2)];
291 | c1 = (c1 & 0x03) << 4;
292 | if (p >= data + len) {
293 | *bp++ = Base64Code[c1];
294 | break;
295 | }
296 | c2 = *p++;
297 | c1 |= (c2 >> 4) & 0x0f;
298 | *bp++ = Base64Code[c1];
299 | c1 = (c2 & 0x0f) << 2;
300 | if (p >= data + len) {
301 | *bp++ = Base64Code[c1];
302 | break;
303 | }
304 | c2 = *p++;
305 | c1 |= (c2 >> 6) & 0x03;
306 | *bp++ = Base64Code[c1];
307 | *bp++ = Base64Code[c2 & 0x3f];
308 | }
309 | *bp = '\0';
310 | return 0;
311 | }
312 |
--------------------------------------------------------------------------------
/Sources/CBcrypt/blf.c:
--------------------------------------------------------------------------------
1 | /* $OpenBSD: blf.c,v 1.7 2007/11/26 09:28:34 martynas Exp $ */
2 |
3 | /*
4 | * Blowfish block cipher for OpenBSD
5 | * Copyright 1997 Niels Provos
6 | * All rights reserved.
7 | *
8 | * Implementation advice by David Mazieres .
9 | *
10 | * Redistribution and use in source and binary forms, with or without
11 | * modification, are permitted provided that the following conditions
12 | * are met:
13 | * 1. Redistributions of source code must retain the above copyright
14 | * notice, this list of conditions and the following disclaimer.
15 | * 2. Redistributions in binary form must reproduce the above copyright
16 | * notice, this list of conditions and the following disclaimer in the
17 | * documentation and/or other materials provided with the distribution.
18 | * 3. All advertising materials mentioning features or use of this software
19 | * must display the following acknowledgement:
20 | * This product includes software developed by Niels Provos.
21 | * 4. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | */
35 |
36 | /*
37 | * This code is derived from section 14.3 and the given source
38 | * in section V of Applied Cryptography, second edition.
39 | * Blowfish is an unpatented fast block cipher designed by
40 | * Bruce Schneier.
41 | */
42 |
43 | #include
44 | #include
45 | #include "blf.h"
46 |
47 | #undef inline
48 | #ifdef __GNUC__
49 | #define inline __inline
50 | #else /* !__GNUC__ */
51 | #define inline
52 | #endif /* !__GNUC__ */
53 |
54 | /* Function for Feistel Networks */
55 |
56 | #define F(s, x) ((((s)[ (((x)>>24)&0xFF)] \
57 | + (s)[0x100 + (((x)>>16)&0xFF)]) \
58 | ^ (s)[0x200 + (((x)>> 8)&0xFF)]) \
59 | + (s)[0x300 + ( (x) &0xFF)])
60 |
61 | #define BLFRND(s,p,i,j,n) (i ^= F(s,j) ^ (p)[n])
62 |
63 | void
64 | Blowfish_encipher(blf_ctx *c, u_int32_t *x)
65 | {
66 | u_int32_t Xl;
67 | u_int32_t Xr;
68 | u_int32_t *s = c->S[0];
69 | u_int32_t *p = c->P;
70 |
71 | Xl = x[0];
72 | Xr = x[1];
73 |
74 | Xl ^= p[0];
75 | BLFRND(s, p, Xr, Xl, 1); BLFRND(s, p, Xl, Xr, 2);
76 | BLFRND(s, p, Xr, Xl, 3); BLFRND(s, p, Xl, Xr, 4);
77 | BLFRND(s, p, Xr, Xl, 5); BLFRND(s, p, Xl, Xr, 6);
78 | BLFRND(s, p, Xr, Xl, 7); BLFRND(s, p, Xl, Xr, 8);
79 | BLFRND(s, p, Xr, Xl, 9); BLFRND(s, p, Xl, Xr, 10);
80 | BLFRND(s, p, Xr, Xl, 11); BLFRND(s, p, Xl, Xr, 12);
81 | BLFRND(s, p, Xr, Xl, 13); BLFRND(s, p, Xl, Xr, 14);
82 | BLFRND(s, p, Xr, Xl, 15); BLFRND(s, p, Xl, Xr, 16);
83 |
84 | x[0] = Xr ^ p[17];
85 | x[1] = Xl;
86 | }
87 |
88 | void
89 | Blowfish_decipher(blf_ctx *c, u_int32_t *x)
90 | {
91 | u_int32_t Xl;
92 | u_int32_t Xr;
93 | u_int32_t *s = c->S[0];
94 | u_int32_t *p = c->P;
95 |
96 | Xl = x[0];
97 | Xr = x[1];
98 |
99 | Xl ^= p[17];
100 | BLFRND(s, p, Xr, Xl, 16); BLFRND(s, p, Xl, Xr, 15);
101 | BLFRND(s, p, Xr, Xl, 14); BLFRND(s, p, Xl, Xr, 13);
102 | BLFRND(s, p, Xr, Xl, 12); BLFRND(s, p, Xl, Xr, 11);
103 | BLFRND(s, p, Xr, Xl, 10); BLFRND(s, p, Xl, Xr, 9);
104 | BLFRND(s, p, Xr, Xl, 8); BLFRND(s, p, Xl, Xr, 7);
105 | BLFRND(s, p, Xr, Xl, 6); BLFRND(s, p, Xl, Xr, 5);
106 | BLFRND(s, p, Xr, Xl, 4); BLFRND(s, p, Xl, Xr, 3);
107 | BLFRND(s, p, Xr, Xl, 2); BLFRND(s, p, Xl, Xr, 1);
108 |
109 | x[0] = Xr ^ p[0];
110 | x[1] = Xl;
111 | }
112 |
113 | void
114 | Blowfish_initstate(blf_ctx *c)
115 | {
116 | /* P-box and S-box tables initialized with digits of Pi */
117 |
118 | static const blf_ctx initstate =
119 |
120 | { {
121 | {
122 | 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
123 | 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
124 | 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
125 | 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
126 | 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
127 | 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
128 | 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
129 | 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
130 | 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
131 | 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
132 | 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
133 | 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
134 | 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
135 | 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
136 | 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
137 | 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
138 | 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
139 | 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
140 | 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
141 | 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
142 | 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
143 | 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
144 | 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
145 | 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
146 | 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
147 | 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
148 | 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
149 | 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
150 | 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
151 | 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
152 | 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
153 | 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
154 | 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
155 | 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
156 | 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
157 | 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
158 | 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
159 | 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
160 | 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
161 | 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
162 | 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
163 | 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
164 | 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
165 | 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
166 | 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
167 | 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
168 | 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
169 | 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
170 | 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
171 | 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
172 | 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
173 | 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
174 | 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
175 | 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
176 | 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
177 | 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
178 | 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
179 | 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
180 | 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
181 | 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
182 | 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
183 | 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
184 | 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
185 | 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a},
186 | {
187 | 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
188 | 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
189 | 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
190 | 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
191 | 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
192 | 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
193 | 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
194 | 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
195 | 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
196 | 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
197 | 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
198 | 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
199 | 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
200 | 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
201 | 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
202 | 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
203 | 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
204 | 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
205 | 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
206 | 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
207 | 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
208 | 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
209 | 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
210 | 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
211 | 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
212 | 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
213 | 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
214 | 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
215 | 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
216 | 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
217 | 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
218 | 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
219 | 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
220 | 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
221 | 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
222 | 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
223 | 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
224 | 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
225 | 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
226 | 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
227 | 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
228 | 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
229 | 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
230 | 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
231 | 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
232 | 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
233 | 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
234 | 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
235 | 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
236 | 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
237 | 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
238 | 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
239 | 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
240 | 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
241 | 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
242 | 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
243 | 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
244 | 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
245 | 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
246 | 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
247 | 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
248 | 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
249 | 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
250 | 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7},
251 | {
252 | 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
253 | 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
254 | 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
255 | 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
256 | 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
257 | 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
258 | 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
259 | 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
260 | 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
261 | 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
262 | 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
263 | 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
264 | 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
265 | 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
266 | 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
267 | 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
268 | 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
269 | 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
270 | 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
271 | 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
272 | 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
273 | 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
274 | 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
275 | 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
276 | 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
277 | 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
278 | 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
279 | 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
280 | 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
281 | 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
282 | 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
283 | 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
284 | 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
285 | 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
286 | 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
287 | 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
288 | 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
289 | 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
290 | 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
291 | 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
292 | 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
293 | 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
294 | 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
295 | 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
296 | 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
297 | 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
298 | 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
299 | 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
300 | 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
301 | 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
302 | 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
303 | 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
304 | 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
305 | 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
306 | 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
307 | 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
308 | 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
309 | 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
310 | 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
311 | 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
312 | 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
313 | 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
314 | 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
315 | 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0},
316 | {
317 | 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
318 | 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
319 | 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
320 | 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
321 | 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
322 | 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
323 | 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
324 | 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
325 | 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
326 | 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
327 | 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
328 | 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
329 | 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
330 | 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
331 | 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
332 | 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
333 | 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
334 | 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
335 | 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
336 | 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
337 | 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
338 | 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
339 | 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
340 | 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
341 | 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
342 | 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
343 | 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
344 | 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
345 | 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
346 | 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
347 | 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
348 | 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
349 | 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
350 | 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
351 | 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
352 | 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
353 | 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
354 | 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
355 | 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
356 | 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
357 | 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
358 | 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
359 | 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
360 | 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
361 | 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
362 | 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
363 | 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
364 | 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
365 | 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
366 | 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
367 | 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
368 | 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
369 | 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
370 | 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
371 | 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
372 | 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
373 | 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
374 | 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
375 | 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
376 | 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
377 | 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
378 | 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
379 | 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
380 | 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6}
381 | },
382 | {
383 | 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
384 | 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
385 | 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
386 | 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
387 | 0x9216d5d9, 0x8979fb1b
388 | } };
389 |
390 | *c = initstate;
391 | }
392 |
393 | u_int32_t
394 | Blowfish_stream2word(const u_int8_t *data, u_int16_t databytes,
395 | u_int16_t *current)
396 | {
397 | u_int8_t i;
398 | u_int16_t j;
399 | u_int32_t temp;
400 |
401 | temp = 0x00000000;
402 | j = *current;
403 |
404 | for (i = 0; i < 4; i++, j++) {
405 | if (j >= databytes)
406 | j = 0;
407 | temp = (temp << 8) | data[j];
408 | }
409 |
410 | *current = j;
411 | return temp;
412 | }
413 |
414 | void
415 | Blowfish_expand0state(blf_ctx *c, const u_int8_t *key, u_int16_t keybytes)
416 | {
417 | u_int16_t i;
418 | u_int16_t j;
419 | u_int16_t k;
420 | u_int32_t temp;
421 | u_int32_t data[2];
422 |
423 | j = 0;
424 | for (i = 0; i < BLF_N + 2; i++) {
425 | /* Extract 4 int8 to 1 int32 from keystream */
426 | temp = Blowfish_stream2word(key, keybytes, &j);
427 | c->P[i] = c->P[i] ^ temp;
428 | }
429 |
430 | j = 0;
431 | data[0] = 0x00000000;
432 | data[1] = 0x00000000;
433 | for (i = 0; i < BLF_N + 2; i += 2) {
434 | Blowfish_encipher(c, data);
435 |
436 | c->P[i] = data[0];
437 | c->P[i + 1] = data[1];
438 | }
439 |
440 | for (i = 0; i < 4; i++) {
441 | for (k = 0; k < 256; k += 2) {
442 | Blowfish_encipher(c, data);
443 |
444 | c->S[i][k] = data[0];
445 | c->S[i][k + 1] = data[1];
446 | }
447 | }
448 | }
449 |
450 |
451 | void
452 | Blowfish_expandstate(blf_ctx *c, const u_int8_t *data, u_int16_t databytes,
453 | const u_int8_t *key, u_int16_t keybytes)
454 | {
455 | u_int16_t i;
456 | u_int16_t j;
457 | u_int16_t k;
458 | u_int32_t temp;
459 | u_int32_t d[2];
460 |
461 | j = 0;
462 | for (i = 0; i < BLF_N + 2; i++) {
463 | /* Extract 4 int8 to 1 int32 from keystream */
464 | temp = Blowfish_stream2word(key, keybytes, &j);
465 | c->P[i] = c->P[i] ^ temp;
466 | }
467 |
468 | j = 0;
469 | d[0] = 0x00000000;
470 | d[1] = 0x00000000;
471 | for (i = 0; i < BLF_N + 2; i += 2) {
472 | d[0] ^= Blowfish_stream2word(data, databytes, &j);
473 | d[1] ^= Blowfish_stream2word(data, databytes, &j);
474 | Blowfish_encipher(c, d);
475 |
476 | c->P[i] = d[0];
477 | c->P[i + 1] = d[1];
478 | }
479 |
480 | for (i = 0; i < 4; i++) {
481 | for (k = 0; k < 256; k += 2) {
482 | d[0]^= Blowfish_stream2word(data, databytes, &j);
483 | d[1] ^= Blowfish_stream2word(data, databytes, &j);
484 | Blowfish_encipher(c, d);
485 |
486 | c->S[i][k] = d[0];
487 | c->S[i][k + 1] = d[1];
488 | }
489 | }
490 |
491 | }
492 |
493 | void
494 | blf_key(blf_ctx *c, const u_int8_t *k, u_int16_t len)
495 | {
496 | /* Initialize S-boxes and subkeys with Pi */
497 | Blowfish_initstate(c);
498 |
499 | /* Transform S-boxes and subkeys with key */
500 | Blowfish_expand0state(c, k, len);
501 | }
502 |
503 | void
504 | blf_enc(blf_ctx *c, u_int32_t *data, u_int16_t blocks)
505 | {
506 | u_int32_t *d;
507 | u_int16_t i;
508 |
509 | d = data;
510 | for (i = 0; i < blocks; i++) {
511 | Blowfish_encipher(c, d);
512 | d += 2;
513 | }
514 | }
515 |
516 | void
517 | blf_dec(blf_ctx *c, u_int32_t *data, u_int16_t blocks)
518 | {
519 | u_int32_t *d;
520 | u_int16_t i;
521 |
522 | d = data;
523 | for (i = 0; i < blocks; i++) {
524 | Blowfish_decipher(c, d);
525 | d += 2;
526 | }
527 | }
528 |
529 | void
530 | blf_ecb_encrypt(blf_ctx *c, u_int8_t *data, u_int32_t len)
531 | {
532 | u_int32_t l, r, d[2];
533 | u_int32_t i;
534 |
535 | for (i = 0; i < len; i += 8) {
536 | l = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3];
537 | r = data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7];
538 | d[0] = l;
539 | d[1] = r;
540 | Blowfish_encipher(c, d);
541 | l = d[0];
542 | r = d[1];
543 | data[0] = l >> 24 & 0xff;
544 | data[1] = l >> 16 & 0xff;
545 | data[2] = l >> 8 & 0xff;
546 | data[3] = l & 0xff;
547 | data[4] = r >> 24 & 0xff;
548 | data[5] = r >> 16 & 0xff;
549 | data[6] = r >> 8 & 0xff;
550 | data[7] = r & 0xff;
551 | data += 8;
552 | }
553 | }
554 |
555 | void
556 | blf_ecb_decrypt(blf_ctx *c, u_int8_t *data, u_int32_t len)
557 | {
558 | u_int32_t l, r, d[2];
559 | u_int32_t i;
560 |
561 | for (i = 0; i < len; i += 8) {
562 | l = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3];
563 | r = data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7];
564 | d[0] = l;
565 | d[1] = r;
566 | Blowfish_decipher(c, d);
567 | l = d[0];
568 | r = d[1];
569 | data[0] = l >> 24 & 0xff;
570 | data[1] = l >> 16 & 0xff;
571 | data[2] = l >> 8 & 0xff;
572 | data[3] = l & 0xff;
573 | data[4] = r >> 24 & 0xff;
574 | data[5] = r >> 16 & 0xff;
575 | data[6] = r >> 8 & 0xff;
576 | data[7] = r & 0xff;
577 | data += 8;
578 | }
579 | }
580 |
581 | void
582 | blf_cbc_encrypt(blf_ctx *c, u_int8_t *iv, u_int8_t *data, u_int32_t len)
583 | {
584 | u_int32_t l, r, d[2];
585 | u_int32_t i, j;
586 |
587 | for (i = 0; i < len; i += 8) {
588 | for (j = 0; j < 8; j++)
589 | data[j] ^= iv[j];
590 | l = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3];
591 | r = data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7];
592 | d[0] = l;
593 | d[1] = r;
594 | Blowfish_encipher(c, d);
595 | l = d[0];
596 | r = d[1];
597 | data[0] = l >> 24 & 0xff;
598 | data[1] = l >> 16 & 0xff;
599 | data[2] = l >> 8 & 0xff;
600 | data[3] = l & 0xff;
601 | data[4] = r >> 24 & 0xff;
602 | data[5] = r >> 16 & 0xff;
603 | data[6] = r >> 8 & 0xff;
604 | data[7] = r & 0xff;
605 | iv = data;
606 | data += 8;
607 | }
608 | }
609 |
610 | void
611 | blf_cbc_decrypt(blf_ctx *c, u_int8_t *iva, u_int8_t *data, u_int32_t len)
612 | {
613 | u_int32_t l, r, d[2];
614 | u_int8_t *iv;
615 | u_int32_t i, j;
616 |
617 | iv = data + len - 16;
618 | data = data + len - 8;
619 | for (i = len - 8; i >= 8; i -= 8) {
620 | l = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3];
621 | r = data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7];
622 | d[0] = l;
623 | d[1] = r;
624 | Blowfish_decipher(c, d);
625 | l = d[0];
626 | r = d[1];
627 | data[0] = l >> 24 & 0xff;
628 | data[1] = l >> 16 & 0xff;
629 | data[2] = l >> 8 & 0xff;
630 | data[3] = l & 0xff;
631 | data[4] = r >> 24 & 0xff;
632 | data[5] = r >> 16 & 0xff;
633 | data[6] = r >> 8 & 0xff;
634 | data[7] = r & 0xff;
635 | for (j = 0; j < 8; j++)
636 | data[j] ^= iv[j];
637 | iv -= 8;
638 | data -= 8;
639 | }
640 | l = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3];
641 | r = data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7];
642 | d[0] = l;
643 | d[1] = r;
644 | Blowfish_decipher(c, d);
645 | l = d[0];
646 | r = d[1];
647 | data[0] = l >> 24 & 0xff;
648 | data[1] = l >> 16 & 0xff;
649 | data[2] = l >> 8 & 0xff;
650 | data[3] = l & 0xff;
651 | data[4] = r >> 24 & 0xff;
652 | data[5] = r >> 16 & 0xff;
653 | data[6] = r >> 8 & 0xff;
654 | data[7] = r & 0xff;
655 | for (j = 0; j < 8; j++)
656 | data[j] ^= iva[j];
657 | }
658 |
--------------------------------------------------------------------------------
/Sources/CBcrypt/blf.h:
--------------------------------------------------------------------------------
1 | /* $OpenBSD: blf.h,v 1.6 2007/02/21 19:25:40 grunk Exp $ */
2 |
3 | /*
4 | * Blowfish - a fast block cipher designed by Bruce Schneier
5 | *
6 | * Copyright 1997 Niels Provos
7 | * All rights reserved.
8 | *
9 | * Redistribution and use in source and binary forms, with or without
10 | * modification, are permitted provided that the following conditions
11 | * are met:
12 | * 1. Redistributions of source code must retain the above copyright
13 | * notice, this list of conditions and the following disclaimer.
14 | * 2. Redistributions in binary form must reproduce the above copyright
15 | * notice, this list of conditions and the following disclaimer in the
16 | * documentation and/or other materials provided with the distribution.
17 | * 3. All advertising materials mentioning features or use of this software
18 | * must display the following acknowledgement:
19 | * This product includes software developed by Niels Provos.
20 | * 4. The name of the author may not be used to endorse or promote products
21 | * derived from this software without specific prior written permission.
22 | *
23 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 | */
34 |
35 | #ifndef _BLF_H_
36 | #define _BLF_H_
37 |
38 | /* Schneier states the maximum key length to be 56 bytes.
39 | * The way how the subkeys are initialized by the key up
40 | * to (N+2)*4 i.e. 72 bytes are utilized.
41 | * Warning: For normal blowfish encryption only 56 bytes
42 | * of the key affect all cipherbits.
43 | */
44 |
45 | #define BLF_N 16 /* Number of Subkeys */
46 | #define BLF_MAXKEYLEN ((BLF_N-2)*4) /* 448 bits */
47 | #define BLF_MAXUTILIZED ((BLF_N+2)*4) /* 576 bits */
48 |
49 | /* Blowfish context */
50 | typedef struct BlowfishContext {
51 | u_int32_t S[4][256]; /* S-Boxes */
52 | u_int32_t P[BLF_N + 2]; /* Subkeys */
53 | } blf_ctx;
54 |
55 | /* Raw access to customized Blowfish
56 | * blf_key is just:
57 | * Blowfish_initstate( state )
58 | * Blowfish_expand0state( state, key, keylen )
59 | */
60 |
61 | void Blowfish_encipher(blf_ctx *, u_int32_t *);
62 | void Blowfish_decipher(blf_ctx *, u_int32_t *);
63 | void Blowfish_initstate(blf_ctx *);
64 | void Blowfish_expand0state(blf_ctx *, const u_int8_t *, u_int16_t);
65 | void Blowfish_expandstate(blf_ctx *, const u_int8_t *, u_int16_t, const u_int8_t *, u_int16_t);
66 |
67 | /* Standard Blowfish */
68 |
69 | void blf_key(blf_ctx *, const u_int8_t *, u_int16_t);
70 | void blf_enc(blf_ctx *, u_int32_t *, u_int16_t);
71 | void blf_dec(blf_ctx *, u_int32_t *, u_int16_t);
72 |
73 | /* Converts u_int8_t to u_int32_t */
74 | u_int32_t Blowfish_stream2word(const u_int8_t *, u_int16_t ,
75 | u_int16_t *);
76 |
77 | void blf_ecb_encrypt(blf_ctx *, u_int8_t *, u_int32_t);
78 | void blf_ecb_decrypt(blf_ctx *, u_int8_t *, u_int32_t);
79 |
80 | void blf_cbc_encrypt(blf_ctx *, u_int8_t *, u_int8_t *, u_int32_t);
81 | void blf_cbc_decrypt(blf_ctx *, u_int8_t *, u_int8_t *, u_int32_t);
82 | #endif
83 |
--------------------------------------------------------------------------------
/Sources/CBcrypt/include/bcrypt.h:
--------------------------------------------------------------------------------
1 | /* $OpenBSD: bcrypt.c,v 1.58 2020/07/06 13:33:05 pirofti Exp $ */
2 |
3 | /*
4 | * Copyright (c) 2014 Ted Unangst
5 | * Copyright (c) 1997 Niels Provos
6 | *
7 | * Permission to use, copy, modify, and distribute this software for any
8 | * purpose with or without fee is hereby granted, provided that the above
9 | * copyright notice and this permission notice appear in all copies.
10 | *
11 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 | */
19 | /* This password hashing algorithm was designed by David Mazieres
20 | * and works as follows:
21 | *
22 | * 1. state := InitState ()
23 | * 2. state := ExpandKey (state, salt, password)
24 | * 3. REPEAT rounds:
25 | * state := ExpandKey (state, 0, password)
26 | * state := ExpandKey (state, 0, salt)
27 | * 4. ctext := "OrpheanBeholderScryDoubt"
28 | * 5. REPEAT 64:
29 | * ctext := Encrypt_ECB (state, ctext);
30 | * 6. RETURN Concatenate (salt, ctext);
31 | *
32 | */
33 |
34 | #include
35 | #include
36 | #include
37 |
38 | #define BCRYPT_VERSION '2'
39 | #define BCRYPT_MAXSALT 16 /* Precomputation is just so nice */
40 | #define BCRYPT_WORDS 6 /* Ciphertext words */
41 | #define BCRYPT_MINLOGROUNDS 4 /* we have log2(rounds) in salt */
42 |
43 | #define BCRYPT_SALTSPACE 30 /* (7 + (BCRYPT_MAXSALT * 4 + 2) / 3 + 1) */
44 | #define BCRYPT_HASHSPACE 61
45 |
46 | /// generate salt given a cost and random buffer of 16 bytes
47 | int c_hb_bcrypt_initsalt_with_csalt(int log_rounds, char *salt, size_t saltbuflen, const uint8_t *csalt);
48 | /// encrypt `pass` using `salt`
49 | int c_hb_bcrypt_hashpass(const char *key, const char *salt, char *encrypted, size_t encryptedlen);
50 | /// check `pass` against hash
51 | int c_hb_bcrypt_checkpass(const char *pass, const char *goodhash);
52 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuth/Authenticator/AuthRequestContext.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2023 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import Hummingbird
16 | import Logging
17 | import NIOConcurrencyHelpers
18 | import NIOCore
19 |
20 | /// Protocol that all request contexts should conform to if they want to support
21 | /// authentication middleware
22 | public protocol AuthRequestContext: RequestContext {
23 | associatedtype Identity: Sendable
24 |
25 | /// The authenticated identity
26 | var identity: Identity? { get set }
27 | }
28 |
29 | extension AuthRequestContext {
30 | /// Return Identity attached to context.
31 | ///
32 | /// If Identity does not exist then throw a 401 (Unauthorized) status
33 | public func requireIdentity() throws -> Identity {
34 | guard let identity = self.identity else { throw HTTPError(.unauthorized, message: "Authenticated identity is unavailable") }
35 | return identity
36 | }
37 | }
38 |
39 | /// Implementation of a basic request context that supports authenticators
40 | public struct BasicAuthRequestContext: AuthRequestContext, RequestContext {
41 | /// core context
42 | public var coreContext: CoreRequestContextStorage
43 | /// The authenticated identity
44 | public var identity: Identity?
45 |
46 | /// Initialize an `RequestContext`
47 | /// - Parameters:
48 | /// - applicationContext: Context from Application that instigated the request
49 | /// - channel: Channel that generated this request
50 | /// - logger: Logger
51 | public init(source: Source) {
52 | self.coreContext = .init(source: source)
53 | self.identity = nil
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuth/Authenticator/Authenticator.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2023 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import Hummingbird
16 | import NIOCore
17 |
18 | /// Protocol for a middleware that checks if a request is authenticated.
19 | ///
20 | /// Requires an `authenticate` function that returns authentication data when successful.
21 | /// If it is unsuccessful then nil should be returned so middleware further down the
22 | /// middleware chain can do authentication. If you don't want any further middleware to
23 | /// run then throw an error.
24 | ///
25 | /// To use an authenticator middleware it is required that your request context conform to
26 | /// ``AuthRequestContext`` so the middleware can attach authentication data to
27 | /// ``AuthRequestContext/identity-swift.property``.
28 | ///
29 | /// A simple username, password authenticator could be implemented as follows. If the
30 | /// authenticator is successful it returns a `User` struct, otherwise it returns `nil`.
31 | ///
32 | /// ```swift
33 | /// struct BasicAuthenticator: AuthenticatorMiddleware {
34 | /// func authenticate(request: Request, context: Context) async throws -> User? {
35 | /// // Basic authentication info in the "Authorization" header, is accessible
36 | /// // via request.headers.basic
37 | /// guard let basic = request.headers.basic else { return nil }
38 | /// // check if user exists in the database
39 | /// guard let user = try await database.getUserWithUsername(basic.username) else {
40 | /// return nil
41 | /// }
42 | /// // verify password against password hash stored in database. If valid
43 | /// // return the user. HummingbirdAuth provides an implementation of Bcrypt
44 | /// // This should be run on the thread pool as it is a long process.
45 | /// return try await context.threadPool.runIfActive {
46 | /// if Bcrypt.verify(basic.password, hash: user.passwordHash) {
47 | /// return user
48 | /// }
49 | /// return nil
50 | /// }
51 | /// }
52 | /// }
53 | /// ```
54 | public protocol AuthenticatorMiddleware: RouterMiddleware where Context: AuthRequestContext {
55 | /// Type to be authenticated
56 | associatedtype Identity: Sendable
57 | /// Called by middleware to see if request can authenticate.
58 | ///
59 | /// Should return an object if authenticated, return nil is not authenticated
60 | /// but want the request to be passed onto the next middleware or the router, or throw an error
61 | /// if the request should not proceed any further
62 | func authenticate(request: Request, context: Context) async throws -> Identity?
63 | }
64 |
65 | extension AuthenticatorMiddleware {
66 | /// Calls `authenticate` and if it returns a valid object `login` with this object
67 | @inlinable
68 | public func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response {
69 | if let authenticated = try await authenticate(request: request, context: context) {
70 | var context = context
71 | context.identity = authenticated
72 | return try await next(request, context)
73 | } else {
74 | return try await next(request, context)
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuth/Authenticator/ClosureAuthenticator.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2023 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import Hummingbird
16 | import NIOCore
17 |
18 | /// Authenticator that uses a closure to return authentication state
19 | public struct ClosureAuthenticator<
20 | Context: AuthRequestContext
21 | >: AuthenticatorMiddleware {
22 | public typealias Identity = Context.Identity
23 |
24 | let closure: @Sendable (Request, Context) async throws -> Context.Identity?
25 |
26 | public init(_ closure: @escaping @Sendable (Request, Context) async throws -> Context.Identity?) {
27 | self.closure = closure
28 | }
29 |
30 | public func authenticate(request: Request, context: Context) async throws -> Context.Identity? {
31 | try await self.closure(request, context)
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuth/BasicAuthentication.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2021 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import ExtrasBase64
16 | import HTTPTypes
17 | import Hummingbird
18 |
19 | /// Basic authentication information extracted from request header "Authorization"
20 | public struct BasicAuthentication: Sendable {
21 | public let username: String
22 | public let password: String
23 | }
24 |
25 | extension HTTPFields {
26 | /// Return Basic (username/password) authorization information from request
27 | public var basic: BasicAuthentication? {
28 | // check for authorization header
29 | guard let authorization = self[.authorization] else { return nil }
30 | // check for basic prefix
31 | guard authorization.hasPrefix("Basic ") else { return nil }
32 | // extract base64 data
33 | let base64 = String(authorization.dropFirst("Basic ".count))
34 | // decode base64
35 | guard let data = try? base64.base64decoded() else { return nil }
36 | // create string from data
37 | let usernamePassword = String(decoding: data, as: Unicode.UTF8.self)
38 | // split string
39 | let split = usernamePassword.split(separator: ":", maxSplits: 1)
40 | // need two splits
41 | guard split.count == 2 else { return nil }
42 | return .init(username: String(split[0]), password: String(split[1]))
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuth/BearerAuthentication.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2021 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import HTTPTypes
16 | import Hummingbird
17 |
18 | /// Bearer authentication information extracted from request header "Authorization"
19 | public struct BearerAuthentication: Sendable {
20 | public let token: String
21 | }
22 |
23 | extension HTTPFields {
24 | /// Return Bearer authorization information from request
25 | public var bearer: BearerAuthentication? {
26 | // check for authorization header
27 | guard let authorization = self[.authorization] else { return nil }
28 | // check for bearer prefix
29 | guard authorization.hasPrefix("Bearer ") else { return nil }
30 | // return token
31 | return .init(token: String(authorization.dropFirst("Bearer ".count)))
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuth/Deprecated.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2024 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | // Below is a list of unavailable symbols with the "HB" prefix. These are available
16 | // temporarily to ease transition from the old symbols that included the "HB"
17 | // prefix to the new ones.
18 | @_documentation(visibility: internal) @available(*, unavailable, renamed: "AuthRequestContext")
19 | public typealias HBAuthRequestContext = AuthRequestContext
20 | @_documentation(visibility: internal) @available(*, unavailable, renamed: "Sendable")
21 | public typealias Authenticatable = Sendable
22 | @_documentation(visibility: internal) @available(*, unavailable, renamed: "BasicAuthRequestContext")
23 | public typealias HBBasicAuthRequestContext = BasicAuthRequestContext
24 |
25 | @_documentation(visibility: internal) @available(*, unavailable, renamed: "Sendable")
26 | public typealias HBAuthenticatable = Sendable
27 | @_documentation(visibility: internal) @available(*, unavailable, renamed: "AuthenticatorMiddleware")
28 | public typealias HBAuthenticator = AuthenticatorMiddleware
29 | @_documentation(visibility: internal) @available(*, unavailable, renamed: "SessionAuthenticator")
30 | public typealias HBSessionAuthenticator = SessionAuthenticator
31 | @_documentation(visibility: internal) @available(*, unavailable, renamed: "SessionStorage")
32 | public typealias HBSessionStorage = SessionStorage
33 |
34 | @_documentation(visibility: internal) @available(*, deprecated, renamed: "UserSessionRepository")
35 | public typealias SessionUserRepository = UserSessionRepository
36 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuth/Middleware/IsAuthenticatedMiddleware.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2021 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import Hummingbird
16 |
17 | /// Middleware returning 401 for unauthenticated requests
18 | public struct IsAuthenticatedMiddleware: RouterMiddleware {
19 | public init() {}
20 |
21 | public func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response {
22 | guard context.identity != nil else {
23 | throw HTTPError(.unauthorized)
24 | }
25 | return try await next(request, context)
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuth/Sessions/SessionAuthenticator.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2024 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import Hummingbird
16 |
17 | /// Session authenticator
18 | ///
19 | /// The `SessionAuthenticator` needs to have the ``SessionMiddleware`` before it in the middleware
20 | /// chain to extract session information for the request
21 | public struct SessionAuthenticator<
22 | Context: AuthRequestContext & SessionRequestContext,
23 | Repository: UserSessionRepository
24 | >: AuthenticatorMiddleware {
25 | public typealias Identity = Context.Identity
26 |
27 | /// User repository
28 | public let users: Repository
29 |
30 | /// Initialize SessionAuthenticator middleware
31 | /// - Parameters:
32 | /// - users: User repository
33 | /// - context: Request context type
34 | public init(users: Repository, context: Context.Type = Context.self) {
35 | self.users = users
36 | }
37 |
38 | /// Initialize SessionAuthenticator middleware
39 | /// - Parameters:
40 | /// - context: Request context type
41 | /// - getUser: Closure returning user type from session id
42 | public init(
43 | context: Context.Type = Context.self,
44 | getUser: @escaping @Sendable (Session, UserRepositoryContext) async throws -> Context.Identity?
45 | ) where Repository == UserSessionClosureRepository {
46 | self.users = UserSessionClosureRepository(getUser)
47 | }
48 |
49 | @inlinable
50 | public func authenticate(request: Request, context: Context) async throws -> Repository.User? {
51 | if let session = context.sessions.session {
52 | return try await self.users.getUser(from: session, context: .init(logger: context.logger))
53 | } else {
54 | return nil
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuth/Sessions/SessionContext.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2024 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import Foundation
16 | import Hummingbird
17 | import NIOConcurrencyHelpers
18 |
19 | /// Session data
20 | @dynamicMemberLookup
21 | public struct SessionData: Codable, Sendable {
22 | @usableFromInline
23 | var object: Session
24 | @usableFromInline
25 | var edited: Bool
26 | /// When session will expire
27 | public var expiresIn: Duration?
28 |
29 | @usableFromInline
30 | init(value: Session, expiresIn: Duration?) {
31 | self.object = value
32 | self.edited = true
33 | self.expiresIn = expiresIn
34 | }
35 |
36 | /// Codable decode initializer
37 | public init(from decoder: any Decoder) throws {
38 | let container = try decoder.singleValueContainer()
39 | self.object = try container.decode(Session.self)
40 | self.edited = false
41 | self.expiresIn = nil
42 | }
43 |
44 | /// Codable encode
45 | public func encode(to encoder: any Encoder) throws {
46 | var container = encoder.singleValueContainer()
47 | try container.encode(self.object)
48 | }
49 |
50 | /// Dynamic member lookup. Sets `edited` state if value in `object` is mutated.
51 | @inlinable
52 | public subscript(dynamicMember keyPath: WritableKeyPath) -> T {
53 | get {
54 | self.object[keyPath: keyPath]
55 | }
56 | set {
57 | self.object[keyPath: keyPath] = newValue
58 | self.edited = true
59 | }
60 | }
61 | }
62 |
63 | /// Session context
64 | ///
65 | /// Holds reference to session data protected by a lock to avoid concurrent access
66 | public struct SessionContext: Sendable {
67 | @usableFromInline
68 | let _storage: NIOLockedValueBox?>
69 |
70 | /// Initialize `SessionContext`
71 | @inlinable
72 | public init() {
73 | self._storage = .init(nil)
74 | }
75 |
76 | /// Set session data
77 | /// - Parameters:
78 | /// - session: Session data
79 | /// - expiresIn: How long before session data expires
80 | @inlinable
81 | public func setSession(_ session: Session, expiresIn: Duration? = nil) {
82 | self._storage.withLockedValue {
83 | $0 = .init(value: session, expiresIn: expiresIn)
84 | }
85 | }
86 |
87 | /// Clear session data
88 | @inlinable
89 | public func clearSession() {
90 | self._storage.withLockedValue {
91 | $0 = nil
92 | }
93 | }
94 |
95 | /// Get a copy of the session data
96 | @inlinable
97 | public var session: Session? { self._storage.withLockedValue { $0?.object } }
98 |
99 | /// Access the session and allowing it to be mutated
100 | @inlinable
101 | public func withLockedSession(_ mutate: (inout SessionData?) -> Value) -> Value {
102 | self._storage.withLockedValue {
103 | mutate(&$0)
104 | }
105 | }
106 |
107 | /// Internal access to full session data. Used by `SessionMiddleware`.
108 | var sessionData: SessionData? {
109 | get { self._storage.withLockedValue { $0 } }
110 | nonmutating set { self._storage.withLockedValue { $0 = newValue } }
111 | }
112 | }
113 |
114 | /// Protocol for RequestContext that stores session data
115 | ///
116 | /// The `Session` associatedtype is the data stored in your session. This could be
117 | /// as simple as a `UUID`` that is used to extract a user from a database to a
118 | /// struct containing support for multiple authentication flows.
119 | public protocol SessionRequestContext: RequestContext {
120 | associatedtype Session: Sendable & Codable
121 | var sessions: SessionContext { get }
122 | }
123 |
124 | /// Implementation of a basic request context that supports session storage and authenticators
125 | public struct BasicSessionRequestContext<
126 | Session,
127 | Identity: Sendable
128 | >: AuthRequestContext, SessionRequestContext, RequestContext where Session: Sendable & Codable {
129 | /// core context
130 | public var coreContext: CoreRequestContextStorage
131 | /// The authenticated identity
132 | public var identity: Identity?
133 | /// Session
134 | public let sessions: SessionContext
135 |
136 | /// Initialize an `RequestContext`
137 | /// - Parameters:
138 | /// - applicationContext: Context from Application that instigated the request
139 | /// - channel: Channel that generated this request
140 | /// - logger: Logger
141 | public init(source: Source) {
142 | self.coreContext = .init(source: source)
143 | self.identity = nil
144 | self.sessions = .init()
145 | }
146 | }
147 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuth/Sessions/SessionMiddleware.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2024 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import Hummingbird
16 |
17 | /// Middleware that extracts session data for a request and stores it in the context
18 | ///
19 | /// The `SessionMiddleware` requires that the request context conform to ``SessionRequestContext``.
20 | ///
21 | /// The middleware extracts the session data from storage based off the session cookie in the
22 | /// request. If after returning from running the rest of the middleware chain the session data
23 | /// is flagged as being edited it will save it into the session storage and in the case this is
24 | /// a new session will set the "Set-Cookie" header.
25 | public struct SessionMiddleware: RouterMiddleware {
26 | /// Storage for session data
27 | let sessionStorage: SessionStorage
28 |
29 | /// Default duration for a session token
30 | let defaultSessionExpiration: Duration
31 |
32 | /// Initialize SessionMiddleware
33 | /// - Parameters:
34 | /// - storage: Persist driver to use for storage
35 | /// - sessionCookie: Session cookie name
36 | /// - defaultSessionExpiration: Default expiration for session data
37 | public init(storage: any PersistDriver, sessionCookie: String = "SESSION_ID", defaultSessionExpiration: Duration = .seconds(60 * 60 * 12)) {
38 | self.sessionStorage = .init(storage, sessionCookie: sessionCookie)
39 | self.defaultSessionExpiration = defaultSessionExpiration
40 | }
41 |
42 | /// Initialize SessionMiddleware
43 | /// - Parameters:
44 | /// - storage: Persist driver to use for storage
45 | /// - sessionCookieParameters: Session cookie parameters
46 | /// - defaultSessionExpiration: Default expiration for session data
47 | public init(
48 | storage: any PersistDriver,
49 | sessionCookieParameters: SessionCookieParameters,
50 | defaultSessionExpiration: Duration = .seconds(60 * 60 * 12)
51 | ) {
52 | self.sessionStorage = .init(storage, sessionCookieParameters: sessionCookieParameters)
53 | self.defaultSessionExpiration = defaultSessionExpiration
54 | }
55 |
56 | /// Initialize Session Middleware
57 | /// - Parameters:
58 | /// - sessionStorage: Session storage
59 | /// - defaultSessionExpiration: Default expiration for session data
60 | public init(sessionStorage: SessionStorage, defaultSessionExpiration: Duration = .seconds(60 * 60 * 12)) {
61 | self.sessionStorage = sessionStorage
62 | self.defaultSessionExpiration = defaultSessionExpiration
63 | }
64 |
65 | /// Session Middleware handler
66 | public func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response {
67 | var originalSessionData: Context.Session? = nil
68 | var removeSession = false
69 | do {
70 | originalSessionData = try await self.sessionStorage.load(request: request)
71 | } catch let error as SessionStorage.Error where error == .sessionInvalidType {
72 | context.logger.trace("Failed to convert session data")
73 | removeSession = true
74 | } catch {
75 | context.logger.debug("Failed to load session data")
76 | }
77 | if let originalSessionData {
78 | context.sessions.sessionData = SessionData(
79 | value: originalSessionData,
80 | expiresIn: nil
81 | )
82 | }
83 | var response = try await next(request, context)
84 | let sessionData = context.sessions.sessionData
85 | if let sessionData {
86 | // if session has been edited then store new session
87 | if sessionData.edited {
88 | do {
89 | if let cookie = try await self.sessionStorage.updateAndCreateCookie(
90 | session: sessionData.object,
91 | expiresIn: sessionData.expiresIn,
92 | request: request
93 | ) {
94 | response.headers[values: .setCookie].append(cookie.description)
95 | }
96 | } catch let error as SessionStorage.Error where error == .sessionDoesNotExist {
97 | let cookie = try await self.sessionStorage.save(
98 | session: sessionData.object,
99 | expiresIn: sessionData.expiresIn ?? self.defaultSessionExpiration
100 | )
101 | response.headers[values: .setCookie].append(cookie.description)
102 | }
103 | }
104 | } else if originalSessionData != nil || removeSession {
105 | // if we had a session and we don't anymore, set session to expire
106 | let cookie = try await self.sessionStorage.delete(request: request)
107 | // As the session and cookie expiration has been updated, set the "Set-Cookie" header
108 | response.headers[values: .setCookie].append(cookie.description)
109 | }
110 | return response
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuth/Sessions/SessionStorage.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2022 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import ExtrasBase64
16 | import Foundation
17 | import Hummingbird
18 |
19 | /// Session cookie parameters
20 | public struct SessionCookieParameters: Sendable {
21 | public var name: String
22 | public var domain: String?
23 | public var path: String?
24 | public var secure: Bool
25 | public var sameSite: Cookie.SameSite?
26 |
27 | public init(
28 | name: String = "SESSION_ID",
29 | domain: String? = nil,
30 | path: String = "/",
31 | secure: Bool = false,
32 | sameSite: Cookie.SameSite? = nil
33 | ) {
34 | self.name = name
35 | self.domain = domain
36 | self.path = path
37 | self.secure = secure
38 | self.sameSite = sameSite
39 | }
40 | }
41 |
42 | /// Stores session data
43 | public struct SessionStorage: Sendable {
44 | /// SessionStorage Errors
45 | public struct Error: Swift.Error, Equatable {
46 | enum ErrorType {
47 | case sessionDoesNotExist
48 | case sessionInvalidType
49 | }
50 |
51 | let type: ErrorType
52 | private init(_ type: ErrorType) {
53 | self.type = type
54 | }
55 |
56 | /// Session does not exist
57 | public static var sessionDoesNotExist: Self { .init(.sessionDoesNotExist) }
58 | /// Session was an invalid type
59 | public static var sessionInvalidType: Self { .init(.sessionInvalidType) }
60 | }
61 |
62 | let sessionCookieParameters: SessionCookieParameters
63 | let storage: any PersistDriver
64 |
65 | /// Initialize session storage
66 | /// - Parameters:
67 | /// - storage: Session cookie storage
68 | /// - sessionCookie: Session cookie name
69 | public init(_ storage: any PersistDriver, sessionCookie: String = "SESSION_ID") {
70 | self.storage = storage
71 | self.sessionCookieParameters = .init(name: sessionCookie)
72 | }
73 |
74 | /// Initialize session storage
75 | /// - Parameters:
76 | /// - storage: Session cookie storage
77 | /// - sessionCookieParameters: Session cookie parameters
78 | public init(
79 | _ storage: any PersistDriver,
80 | sessionCookieParameters: SessionCookieParameters
81 | ) {
82 | self.storage = storage
83 | self.sessionCookieParameters = sessionCookieParameters
84 | }
85 |
86 | /// save new or exising session
87 | ///
88 | /// Saving a new session will create a new session id and returns a cookie setting
89 | /// the session id. You need to then return a response including this cookie. You
90 | /// can either create an ``HummingbirdCore/Response`` directly or use ``Hummingbird/EditedResponse`` to
91 | /// generate the response from another type.
92 | /// ```swift
93 | /// let cookie = try await sessionStorage.save(session: session, expiresIn: .seconds(600))
94 | /// var response = EditedResponse(response: responseGenerator)
95 | /// response.setCookie(cookie)
96 | /// return response
97 | /// ```
98 | /// If you know a session already exists it is preferable to use
99 | /// ``SessionStorage/update(session:expiresIn:request:)``.
100 | public func save(session: SessionType, expiresIn: Duration) async throws -> Cookie {
101 | let sessionId = Self.createSessionId()
102 | // prefix with "hbs."
103 | try await self.storage.set(
104 | key: "hbs.\(sessionId)",
105 | value: session,
106 | expires: expiresIn
107 | )
108 | return self.createSessionCookie(sessionId: sessionId, expiresIn: expiresIn)
109 | }
110 |
111 | /// update existing session
112 | ///
113 | /// If session does not exist then a `sessionDoesNotExist` error will be thrown
114 | public func update(session: SessionType, expiresIn: Duration?, request: Request) async throws {
115 | guard let sessionId = self.getId(request: request) else {
116 | throw Error.sessionDoesNotExist
117 | }
118 | // prefix with "hbs."
119 | try await self.storage.set(
120 | key: "hbs.\(sessionId)",
121 | value: session,
122 | expires: expiresIn
123 | )
124 | }
125 |
126 | /// update existing session and return cookie if expiration date is set
127 | ///
128 | /// If session does not exist then a `sessionDoesNotExist` error will be thrown
129 | internal func updateAndCreateCookie(session: SessionType, expiresIn: Duration?, request: Request) async throws -> Cookie? {
130 | guard let sessionId = self.getId(request: request) else {
131 | throw Error.sessionDoesNotExist
132 | }
133 | // prefix with "hbs."
134 | try await self.storage.set(
135 | key: "hbs.\(sessionId)",
136 | value: session,
137 | expires: expiresIn
138 | )
139 | guard let expiresIn else { return nil }
140 | return self.createSessionCookie(sessionId: sessionId, expiresIn: expiresIn)
141 | }
142 |
143 | /// load session
144 | public func load(request: Request) async throws -> SessionType? {
145 | guard let sessionId = getId(request: request) else { return nil }
146 | do {
147 | // prefix with "hbs."
148 | return try await self.storage.get(
149 | key: "hbs.\(sessionId)",
150 | as: SessionType.self
151 | )
152 | } catch let error as PersistError where error == .invalidConversion {
153 | throw Error.sessionInvalidType
154 | }
155 | }
156 |
157 | /// Delete session
158 | /// - Parameter request: Request session is attached to
159 | /// - Returns: Expired cookie
160 | public func delete(request: Request) async throws -> Cookie {
161 | guard let sessionId = getId(request: request) else {
162 | throw Error.sessionDoesNotExist
163 | }
164 | // prefix with "hbs."
165 | try await self.storage.remove(
166 | key: "hbs.\(sessionId)"
167 | )
168 | return self.createSessionCookie(sessionId: sessionId, expiresIn: .seconds(0))
169 | }
170 |
171 | /// Get session id gets id from request
172 | public func getId(request: Request) -> String? {
173 | guard let sessionCookie = request.cookies[self.sessionCookieParameters.name]?.value else { return nil }
174 | return String(sessionCookie)
175 | }
176 |
177 | /// create a session id
178 | static func createSessionId() -> String {
179 | let bytes: [UInt8] = (0..<32).map { _ in UInt8.random(in: 0...255) }
180 | return String(base64Encoding: bytes)
181 | }
182 |
183 | func createSessionCookie(sessionId: String, expiresIn: Duration) -> Cookie {
184 | // accuracy of expires value in cookie only needs to be seconds
185 | let expires = Date.now + TimeInterval(expiresIn.components.seconds)
186 | if let sameSite = self.sessionCookieParameters.sameSite {
187 | return Cookie(
188 | name: self.sessionCookieParameters.name,
189 | value: sessionId,
190 | expires: expires,
191 | domain: self.sessionCookieParameters.domain,
192 | path: self.sessionCookieParameters.path,
193 | secure: self.sessionCookieParameters.secure,
194 | sameSite: sameSite
195 | )
196 | } else {
197 | return Cookie(
198 | name: self.sessionCookieParameters.name,
199 | value: sessionId,
200 | expires: expires,
201 | domain: self.sessionCookieParameters.domain,
202 | path: self.sessionCookieParameters.path,
203 | secure: self.sessionCookieParameters.secure
204 | )
205 | }
206 | }
207 | }
208 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuth/Sessions/UserSessionRepository.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2024 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import Hummingbird
16 | import Logging
17 |
18 | /// Context object supplied when requesting user
19 | public struct UserRepositoryContext {
20 | public let logger: Logger
21 |
22 | @usableFromInline
23 | package init(logger: Logger) {
24 | self.logger = logger
25 | }
26 | }
27 |
28 | /// Repository of users identified by a session object
29 | public protocol UserSessionRepository: Sendable {
30 | associatedtype Identifier: Codable
31 | associatedtype User: Sendable
32 |
33 | /// Get user from repository
34 | /// - Parameters:
35 | /// - id: User ID
36 | /// - context: Request context
37 | /// - Returns: User if there is one associated with supplied id
38 | func getUser(from id: Identifier, context: UserRepositoryContext) async throws -> User?
39 | }
40 |
41 | /// Implementation of UserRepository that uses a closure
42 | public struct UserSessionClosureRepository: UserSessionRepository {
43 | @usableFromInline
44 | let getUserClosure: @Sendable (Identifier, UserRepositoryContext) async throws -> User?
45 |
46 | public init(_ getUserClosure: @escaping @Sendable (Identifier, UserRepositoryContext) async throws -> User?) {
47 | self.getUserClosure = getUserClosure
48 | }
49 |
50 | @inlinable
51 | public func getUser(from id: Identifier, context: UserRepositoryContext) async throws -> User? {
52 | try await self.getUserClosure(id, context)
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Sources/HummingbirdAuthTesting/TestClient+Auth.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2021 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import ExtrasBase64
16 | import Hummingbird
17 | import HummingbirdTesting
18 | import XCTest
19 |
20 | /// Used to generate various authentication types for Testing framework
21 | public struct TestAuthentication: Equatable {
22 | /// create basic authentication test
23 | public static func basic(username: String, password: String) -> Self {
24 | .init(value: .basic(username: username, password: password))
25 | }
26 |
27 | /// create bearer authentication test
28 | public static func bearer(_ token: String) -> Self {
29 | .init(value: .bearer(token))
30 | }
31 |
32 | /// create cookie authentication test
33 | public static func cookie(name: String, value: String) -> Self {
34 | .init(value: .cookie(name: name, value: value))
35 | }
36 |
37 | func apply(
38 | uri: String,
39 | method: HTTPRequest.Method,
40 | headers: HTTPFields,
41 | body: ByteBuffer?
42 | ) -> (uri: String, method: HTTPRequest.Method, headers: HTTPFields, body: ByteBuffer?) {
43 | switch self.value {
44 | case .basic(let username, let password):
45 | var headers = headers
46 | let usernamePassword = "\(username):\(password)"
47 | let authorization = "Basic \(String(base64Encoding: usernamePassword.utf8))"
48 | headers[.authorization] = authorization
49 | return (uri: uri, method: method, headers: headers, body: body)
50 |
51 | case .bearer(let token):
52 | var headers = headers
53 | headers[.authorization] = "Bearer \(token)"
54 | return (uri: uri, method: method, headers: headers, body: body)
55 |
56 | case .cookie(let name, let value):
57 | var headers = headers
58 | let newCookie: String
59 | if let cookie = headers[.cookie] {
60 | newCookie = "\(name)=\(value); \(cookie)"
61 | } else {
62 | newCookie = "\(name)=\(value)"
63 | }
64 | headers[.cookie] = newCookie
65 | return (uri: uri, method: method, headers: headers, body: body)
66 | }
67 | }
68 |
69 | /// Internal type
70 | private enum Internal: Equatable {
71 | case basic(username: String, password: String)
72 | case bearer(String)
73 | case cookie(name: String, value: String)
74 | }
75 |
76 | private let value: Internal
77 | }
78 |
79 | extension TestClientProtocol {
80 | /// Send request with authentication and call test callback on the response returned
81 | ///
82 | /// - Parameters:
83 | /// - uri: URI to test
84 | /// - method: HTTP Method to test
85 | /// - headers: Request headers
86 | /// - auth: Authentication details
87 | /// - body: Request body
88 | /// - testCallback: Callback to test response
89 | /// - Returns: Result of callback
90 | public func execute(
91 | uri: String,
92 | method: HTTPRequest.Method,
93 | headers: HTTPFields = [:],
94 | auth: TestAuthentication,
95 | body: ByteBuffer? = nil,
96 | testCallback: @escaping (TestResponse) throws -> Return
97 | ) async throws -> Return {
98 | let request = auth.apply(uri: uri, method: method, headers: headers, body: body)
99 | return try await self.execute(
100 | uri: request.uri,
101 | method: request.method,
102 | headers: request.headers,
103 | body: request.body,
104 | testCallback: testCallback
105 | )
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/Sources/HummingbirdBasicAuth/BasicAuthenticator.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2024 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import Hummingbird
16 | import HummingbirdAuth
17 |
18 | /// Basic password authenticator
19 | ///
20 | /// Extract username and password from "Authorization" header and checks user exists and that the password is correct
21 | public struct BasicAuthenticator<
22 | Context: AuthRequestContext,
23 | Repository: UserPasswordRepository,
24 | Verifier: PasswordHashVerifier
25 | >: AuthenticatorMiddleware where Context.Identity == Repository.User {
26 | public typealias Identity = Context.Identity
27 |
28 | public let users: Repository
29 | public let passwordHashVerifier: Verifier
30 |
31 | /// Initialize BasicAuthenticator middleware
32 | /// - Parameters:
33 | /// - users: User repository
34 | /// - passwordHashVerifier: password verifier
35 | /// - context: Request context type
36 | public init(users: Repository, passwordHashVerifier: Verifier = BcryptPasswordVerifier(), context: Context.Type = Context.self) {
37 | self.users = users
38 | self.passwordHashVerifier = passwordHashVerifier
39 | }
40 |
41 | /// Initialize BasicAuthenticator middleware
42 | /// - Parameters:
43 | /// - passwordHashVerifier: password verifier
44 | /// - context: Request context type
45 | /// - getUser: Closure returning user type
46 | public init(
47 | passwordHashVerifier: Verifier = BcryptPasswordVerifier(),
48 | context: Context.Type = Context.self,
49 | getUser: @escaping @Sendable (String, UserRepositoryContext) async throws -> Context.Identity?
50 | ) where Identity: PasswordAuthenticatable, Repository == UserPasswordClosureRepository {
51 | self.users = .init(getUser)
52 | self.passwordHashVerifier = passwordHashVerifier
53 | }
54 |
55 | @inlinable
56 | public func authenticate(request: Request, context: Context) async throws -> Repository.User? {
57 | // does request have basic authentication info in the "Authorization" header
58 | guard let basic = request.headers.basic else { return nil }
59 |
60 | // check if user exists and then verify the entered password against the one stored in the database.
61 | // If it is correct then login in user
62 | let user = try await users.getUser(named: basic.username, context: .init(logger: context.logger))
63 | guard let user, let passwordHash = user.passwordHash else { return nil }
64 | // Verify password hash on a separate thread to not block the general task executor
65 | guard try await self.passwordHashVerifier.verifyPassword(basic.password, createsHash: passwordHash) else { return nil }
66 | return user
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Sources/HummingbirdBasicAuth/PasswordVerifier.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2024 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import HummingbirdBcrypt
16 | import NIOPosix
17 |
18 | /// Protocol for password verifier
19 | public protocol PasswordHashVerifier: Sendable {
20 | func verifyPassword(_ password: String, createsHash hash: String) async throws -> Bool
21 | }
22 |
23 | /// Bcrypt password verifier
24 | public struct BcryptPasswordVerifier: PasswordHashVerifier {
25 | public init() {}
26 |
27 | @inlinable
28 | public func verifyPassword(_ password: String, createsHash hash: String) async throws -> Bool {
29 | try await NIOThreadPool.singleton.runIfActive {
30 | Bcrypt.verify(password, hash: hash)
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Sources/HummingbirdBasicAuth/UserPasswordRepository.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2024 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import Hummingbird
16 | import HummingbirdAuth
17 | import Logging
18 |
19 | /// Protocol for password autheticatable object
20 | public protocol PasswordAuthenticatable: Sendable {
21 | var passwordHash: String? { get }
22 | }
23 |
24 | /// Repository of users identified by an id
25 | public protocol UserPasswordRepository: Sendable {
26 | associatedtype User: PasswordAuthenticatable
27 |
28 | /// Get user from repository
29 | /// - Parameters:
30 | /// - id: User ID
31 | /// - context: Request context
32 | /// - Returns: User if there is one associated with supplied id
33 | func getUser(named username: String, context: UserRepositoryContext) async throws -> User?
34 | }
35 |
36 | /// Implementation of UserRepository that uses a closure
37 | public struct UserPasswordClosureRepository: UserPasswordRepository {
38 | @usableFromInline
39 | let getUserClosure: @Sendable (String, UserRepositoryContext) async throws -> User?
40 |
41 | public init(_ getUserClosure: @escaping @Sendable (String, UserRepositoryContext) async throws -> User?) {
42 | self.getUserClosure = getUserClosure
43 | }
44 |
45 | @inlinable
46 | public func getUser(named username: String, context: UserRepositoryContext) async throws -> User? {
47 | try await self.getUserClosure(username, context)
48 | }
49 | }
50 |
51 | @_documentation(visibility: internal) @available(*, deprecated, renamed: "UserPasswordRepository")
52 | public typealias PasswordUserRepository = UserPasswordRepository
53 | @_documentation(visibility: internal) @available(*, deprecated, renamed: "PasswordAuthenticatable")
54 | public typealias BasicAuthenticatorUser = PasswordAuthenticatable
55 |
--------------------------------------------------------------------------------
/Sources/HummingbirdBcrypt/Bcrypt.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2022 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | @_implementationOnly import CBcrypt
16 |
17 | /// Bcrypt password hashing function
18 | ///
19 | /// The Bcrypt hashing function was designed by Niels Provos and David Mazières, based on the Blowfish cipher
20 | /// and presented at USENIX in 1999.[1] Besides incorporating a salt to protect against rainbow table attacks, bcrypt
21 | /// is an adaptive function: over time, the iteration count can be increased to make it slower, so it remains resistant to
22 | /// brute-force search attacks even with increasing computation power.
23 | public enum Bcrypt {
24 | /// Generate bcrypt hash from test
25 | ///
26 | /// The Bcrypt functions are designed to be slow to make them hard to crack. It is best not to run these functions
27 | /// on the default Task executor as this will block other tasks from running. You are better to run them on another
28 | /// thread e.g.
29 | /// ```
30 | /// try await NIOThreadPool.singleton.runIfActive {
31 | /// self.hash(text, cost: cost)
32 | /// }
33 | /// ```
34 | /// - Parameters:
35 | /// - text: original text
36 | /// - cost: log2 iterations of algorithm
37 | /// - Returns: Hashed string
38 | public static func hash(_ text: String, cost: UInt8 = 12) -> String {
39 | guard cost >= BCRYPT_MINLOGROUNDS, cost <= 31 else {
40 | preconditionFailure("Cost should be between 4 and 31")
41 | }
42 |
43 | // create random salt here, instead of using C as arc4random_buf is not always available
44 | let csalt: [UInt8] = (0.. Bool {
75 | c_hb_bcrypt_checkpass(text, hash) == 0
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/Sources/HummingbirdOTP/OTP.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2024 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import Crypto
16 | import ExtrasBase64
17 | import Foundation
18 |
19 | /// HashFunction used in OTP generation
20 | public enum OTPHashFunction: String, Sendable {
21 | case sha1 = "SHA1"
22 | case sha256 = "SHA256"
23 | case sha512 = "SHA512"
24 | }
25 |
26 | /// One time password computation. A one time password is only valid for one login session. OTPs avoid a
27 | /// number of shortcomings that are associated with traditional (static) password-based authentication. OTP
28 | /// generation algorithms typically make use of pseudorandomness or randomness, making prediction of successor
29 | /// OTPs by an attacker difficult, and also cryptographic hash functions, which can be used to derive a value but
30 | /// are hard to reverse and therefore difficult for an attacker to obtain the data that was used for the hash. This is
31 | /// necessary because otherwise it would be easy to predict future OTPs by observing previous ones.
32 | ///
33 | /// OTPs are commonly used as the second part of two-factor authentication.
34 | protocol OTP {
35 | /// Shared secret
36 | var secret: String { get }
37 | /// Length of OTP generated
38 | var length: Int { get }
39 | /// Hash function used to generate OTP
40 | var hashFunction: OTPHashFunction { get }
41 | }
42 |
43 | extension OTP {
44 | /// Create authenticator URL for OTP generator
45 | ///
46 | /// - Parameters:
47 | /// - algorithmName: Name of algorithm
48 | /// - label: Label for URL
49 | /// - issuer: Who issued the URL
50 | /// - parameters: additional parameters
51 | func createAuthenticatorURL(algorithmName: String, label: String, issuer: String?, parameters: [String: String]) -> String {
52 | let base32 = String(base32Encoding: secret.utf8, options: .omitPaddingCharacter)
53 | let label = label.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? label
54 | let issuer = issuer?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? issuer
55 | var url = "otpauth://\(algorithmName)/\(label)?secret=\(base32)"
56 | if let issuer {
57 | url += "&issuer=\(issuer)"
58 | }
59 | url +=
60 | parameters
61 | .map { "&\($0.key)=\($0.value)" }
62 | .joined()
63 | return url
64 | }
65 |
66 | /// compute OTP. Converts hashFunction
67 | func compute(message: [UInt8]) -> Int {
68 | switch hashFunction {
69 | case .sha1:
70 | return self.compute(message: message, hashFunction: Insecure.SHA1())
71 | case .sha256:
72 | return self.compute(message: message, hashFunction: SHA256())
73 | case .sha512:
74 | return self.compute(message: message, hashFunction: SHA512())
75 | }
76 | }
77 |
78 | /// compute OTP
79 | func compute(message: [UInt8], hashFunction: H) -> Int {
80 | let sha1 = HMAC.authenticationCode(for: message, using: SymmetricKey(data: [UInt8](secret.utf8)))
81 | let truncation = sha1.withUnsafeBytes { bytes -> Int in
82 | let offset = Int(bytes[bytes.count - 1] & 0xF)
83 | var v = Int(bytes[offset] & 0x7F) << 24
84 | v += Int(bytes[offset + 1]) << 16
85 | v += Int(bytes[offset + 2]) << 8
86 | v += Int(bytes[offset + 3])
87 | return v
88 | }
89 | func pow(_ value: Int, _ power: Int) -> Int {
90 | repeatElement(value, count: power).reduce(1, *)
91 | }
92 | return truncation % pow(10, length)
93 | }
94 | }
95 |
96 | /// A counter based one time password (OTP)
97 | ///
98 | /// A HOTP uses a counter as the message when computing the OTP. Everytime the user
99 | /// successfully logs in the server and client should update the commonly stored counter so
100 | /// the next login will require a new password.
101 | public struct HOTP: OTP, Sendable {
102 | public let secret: String
103 | public let length: Int
104 | public let hashFunction: OTPHashFunction
105 |
106 | /// Initialize HOTP
107 | ///
108 | /// If you are using the Google AuthenticatorMiddleware you should choose the default values for length and hashFunction
109 | ///
110 | /// - Parameters:
111 | /// - secret: Secret known by client and server
112 | /// - length: Length of password
113 | /// - hashFunction: Hash function to use
114 | public init(secret: String, length: Int = 6, hashFunction: OTPHashFunction = .sha1) {
115 | self.secret = secret
116 | self.length = length
117 | self.hashFunction = hashFunction
118 | }
119 |
120 | /// Compute a HOTP.
121 | /// - Parameters:
122 | /// - counter: counter to use
123 | /// - Returns: HOTP password
124 | public func compute(counter: UInt64) -> Int {
125 | self.compute(message: counter.bigEndian.bytes)
126 | }
127 |
128 | /// Create AuthenticatorMiddleware URL for HOTP generator
129 | ///
130 | /// OTP is used commonly with authenticator apps on the phone. The AuthenticatorMiddleware apps require your
131 | /// secret to be Base32 encoded when you supply it. You can either supply the base32 encoded secret
132 | /// to be copied into the authenticator app or generate a QR Code to be scanned. This generates the
133 | /// URL you should create your QR Code from.
134 | ///
135 | /// - Parameters:
136 | /// - label: Label for URL
137 | /// - issuer: Who issued the URL
138 | public func createAuthenticatorURL(label: String, issuer: String? = nil) -> String {
139 | var parameters: [String: String] = [:]
140 | if self.length != 6 {
141 | parameters["digits"] = String(describing: self.length)
142 | }
143 | if self.hashFunction != .sha1 {
144 | parameters["algorithm"] = self.hashFunction.rawValue
145 | }
146 | return self.createAuthenticatorURL(algorithmName: "totp", label: label, issuer: issuer, parameters: parameters)
147 | }
148 | }
149 |
150 | /// A time based one time password (OTP)
151 | ///
152 | /// A TOTP uses UNIX time ie the number of seconds since 1970 divided by a time step (normally
153 | /// 30 seconds) as the counter in the OTP computation. This means each password is only ever
154 | /// valid for the timeStep and a new password will be generated after that period.
155 | public struct TOTP: OTP, Sendable {
156 | public let secret: String
157 | public let length: Int
158 | public let hashFunction: OTPHashFunction
159 | public let timeStep: Int
160 |
161 | /// Initialize TOTP
162 | ///
163 | /// If you are using the Google AuthenticatorMiddleware you should choose the default values for length, timeStep and hashFunction
164 | ///
165 | /// - Parameters:
166 | /// - secret: Secret known by client and server
167 | /// - length: Length of password
168 | /// - timeStep: Time between each new code
169 | /// - hashFunction: Hash function to use
170 | public init(secret: String, length: Int = 6, timeStep: Int = 30, hashFunction: OTPHashFunction = .sha1) {
171 | self.secret = secret
172 | self.length = length
173 | self.timeStep = timeStep
174 | self.hashFunction = hashFunction
175 | }
176 |
177 | /// Compute a TOTP
178 | ///
179 | /// - Parameters:
180 | /// - date: Date to generate TOTP for
181 | /// - Returns: TOTP password
182 | public func compute(date: Date = Date()) -> Int {
183 | let timeInterval = date.timeIntervalSince1970
184 | let value = UInt64(timeInterval / Double(self.timeStep))
185 | return self.compute(message: value.bigEndian.bytes)
186 | }
187 |
188 | /// Create AuthenticatorMiddleware URL for TOTP generator
189 | ///
190 | /// OTP is used commonly with authenticator apps on the phone. The AuthenticatorMiddleware apps require your
191 | /// secret to be Base32 encoded when you supply it. You can either supply the base32 encoded secret
192 | /// to be copied into the authenticator app or generate a QR Code to be scanned. This generates the
193 | /// URL you should create your QR Code from.
194 | ///
195 | /// - Parameters:
196 | /// - label: Label for URL
197 | /// - issuer: Who issued the URL
198 | public func createAuthenticatorURL(label: String, issuer: String? = nil) -> String {
199 | var parameters: [String: String] = [:]
200 | if self.length != 6 {
201 | parameters["digits"] = String(describing: self.length)
202 | }
203 | if self.hashFunction != .sha1 {
204 | parameters["algorithm"] = self.hashFunction.rawValue
205 | }
206 | if self.timeStep != 30 {
207 | parameters["period"] = String(describing: self.timeStep)
208 | }
209 | return self.createAuthenticatorURL(algorithmName: "totp", label: label, issuer: issuer, parameters: parameters)
210 | }
211 | }
212 |
213 | extension FixedWidthInteger {
214 | /// Return fixed width integer as an array of bytes
215 | var bytes: [UInt8] {
216 | var v = self
217 | return .init(&v, count: MemoryLayout.size)
218 | }
219 | }
220 |
221 | extension [UInt8] {
222 | /// Construct Array of UInt8 by copying memory
223 | init(_ bytes: UnsafeRawPointer, count: Int) {
224 | self.init(unsafeUninitializedCapacity: count) { buffer, c in
225 | for i in 0...self)
30 | router.get { request, _ -> String? in
31 | request.headers.bearer?.token
32 | }
33 | let app = Application(responder: router.buildResponder())
34 | try await app.test(.router) { client in
35 | try await client.execute(uri: "/", method: .get, auth: .bearer("1234567890")) { response in
36 | let body = try XCTUnwrap(response.body)
37 | XCTAssertEqual(String(buffer: body), "1234567890")
38 | }
39 | try await client.execute(uri: "/", method: .get, auth: .basic(username: "adam", password: "1234")) { response in
40 | XCTAssertEqual(response.status, .noContent)
41 | }
42 | }
43 | }
44 |
45 | func testBasic() async throws {
46 | struct User: Sendable {
47 | let name: String
48 | }
49 | let router = Router(context: BasicAuthRequestContext.self)
50 | router.get { request, _ -> String? in
51 | request.headers.basic.map { "\($0.username):\($0.password)" }
52 | }
53 | let app = Application(responder: router.buildResponder())
54 | try await app.test(.router) { client in
55 | try await client.execute(uri: "/", method: .get, auth: .basic(username: "adam", password: "password")) { response in
56 | let body = try XCTUnwrap(response.body)
57 | XCTAssertEqual(String(buffer: body), "adam:password")
58 | }
59 | }
60 | }
61 |
62 | func testBcryptThread() async throws {
63 | struct User: Sendable {
64 | let name: String
65 | }
66 | let persist = MemoryPersistDriver()
67 | let router = Router(context: BasicAuthRequestContext.self)
68 | router.put { request, _ -> HTTPResponse.Status in
69 | guard let basic = request.headers.basic else { throw HTTPError(.unauthorized) }
70 | let hash = try await NIOThreadPool.singleton.runIfActive {
71 | Bcrypt.hash(basic.password)
72 | }
73 | try await persist.set(key: basic.username, value: hash)
74 | return .ok
75 | }
76 | router.post { request, _ -> HTTPResponse.Status in
77 | guard let basic = request.headers.basic else { throw HTTPError(.unauthorized) }
78 | guard let hash = try await persist.get(key: basic.username, as: String.self) else { throw HTTPError(.unauthorized) }
79 | let verified = try await NIOThreadPool.singleton.runIfActive {
80 | Bcrypt.verify(basic.password, hash: hash)
81 | }
82 | if verified {
83 | return .ok
84 | } else {
85 | return .unauthorized
86 | }
87 | }
88 | let app = Application(responder: router.buildResponder())
89 | try await app.test(.router) { client in
90 | try await client.execute(uri: "/", method: .put, auth: .basic(username: "testuser", password: "testpassword123")) { response in
91 | XCTAssertEqual(response.status, .ok)
92 | }
93 | try await client.execute(uri: "/", method: .post, auth: .basic(username: "testuser", password: "testpassword123")) { response in
94 | XCTAssertEqual(response.status, .ok)
95 | }
96 | }
97 | }
98 |
99 | func testAuth() async throws {
100 | struct User: Sendable {
101 | let name: String
102 | }
103 | struct Additional: Sendable {
104 | let something: String
105 | }
106 | let router = Router(context: BasicAuthRequestContext.self)
107 | router.get { _, context -> HTTPResponse.Status in
108 | var context = context
109 | context.identity = User(name: "Test")
110 |
111 | XCTAssertNotNil(context.identity)
112 | XCTAssertEqual(context.identity?.name, "Test")
113 |
114 | context.identity = nil
115 | XCTAssertNil(context.identity)
116 |
117 | return .accepted
118 | }
119 | let app = Application(responder: router.buildResponder())
120 |
121 | try await app.test(.router) { client in
122 | try await client.execute(uri: "/", method: .get) { response in
123 | XCTAssertEqual(response.status, .accepted)
124 | }
125 | }
126 | }
127 |
128 | func testLogin() async throws {
129 | struct User: Sendable {
130 | let name: String
131 | }
132 | struct TestAuthenticator>: AuthenticatorMiddleware {
133 | func authenticate(request: Request, context: Context) async throws -> User? {
134 | User(name: "Adam")
135 | }
136 | }
137 | let router = Router(context: BasicAuthRequestContext.self)
138 | router.middlewares.add(TestAuthenticator())
139 | router.get { _, context -> HTTPResponse.Status in
140 | guard context.identity != nil else { return .unauthorized }
141 | return .ok
142 | }
143 | let app = Application(responder: router.buildResponder())
144 |
145 | try await app.test(.router) { client in
146 | try await client.execute(uri: "/", method: .get) { response in
147 | XCTAssertEqual(response.status, .ok)
148 | }
149 | }
150 | }
151 |
152 | func testClosureAuthenticator() async throws {
153 | struct User: Sendable {
154 | let name: String
155 | }
156 | struct TestAuthenticator>: AuthenticatorMiddleware {
157 | func authenticate(request: Request, context: Context) async throws -> User? {
158 | User(name: "Adam")
159 | }
160 | }
161 | let router = Router(context: BasicAuthRequestContext.self)
162 | router.group()
163 | .add(
164 | middleware: ClosureAuthenticator { request, _ -> User? in
165 | guard let user = request.uri.queryParameters.get("user") else { return nil }
166 | return User(name: user)
167 | }
168 | )
169 | .get("authenticate") { _, context in
170 | let user = try context.requireIdentity()
171 | return user.name
172 | }
173 | let app = Application(responder: router.buildResponder())
174 |
175 | try await app.test(.router) { client in
176 | try await client.execute(uri: "/authenticate?user=john", method: .get) { response in
177 | XCTAssertEqual(response.status, .ok)
178 | XCTAssertEqual(response.body, ByteBuffer(string: "john"))
179 | }
180 | try await client.execute(uri: "/authenticate", method: .get) { response in
181 | XCTAssertEqual(response.status, .unauthorized)
182 | }
183 | }
184 | }
185 |
186 | func testIsAuthenticatedMiddleware() async throws {
187 | struct User: Sendable {
188 | let name: String
189 | }
190 | struct TestAuthenticator>: AuthenticatorMiddleware {
191 | func authenticate(request: Request, context: Context) async throws -> User? {
192 | User(name: "Adam")
193 | }
194 | }
195 | let router = Router(context: BasicAuthRequestContext.self)
196 | router.group()
197 | .add(middleware: TestAuthenticator())
198 | .add(middleware: IsAuthenticatedMiddleware())
199 | .get("authenticated") { _, _ -> HTTPResponse.Status in
200 | .ok
201 | }
202 | router.group()
203 | .add(middleware: IsAuthenticatedMiddleware())
204 | .get("unauthenticated") { _, _ -> HTTPResponse.Status in
205 | .ok
206 | }
207 | let app = Application(responder: router.buildResponder())
208 |
209 | try await app.test(.router) { client in
210 | try await client.execute(uri: "/authenticated", method: .get) { response in
211 | XCTAssertEqual(response.status, .ok)
212 | }
213 | try await client.execute(uri: "/unauthenticated", method: .get) { response in
214 | XCTAssertEqual(response.status, .unauthorized)
215 | }
216 | }
217 | }
218 |
219 | func testBasicAuthenticator() async throws {
220 | struct User: PasswordAuthenticatable {
221 | let username: String
222 | let passwordHash: String?
223 | }
224 |
225 | struct MyUserRepository: UserPasswordRepository {
226 | func getUser(named username: String, context: UserRepositoryContext) -> User? {
227 | self.users[username].map { .init(username: username, passwordHash: $0) }
228 | }
229 |
230 | let users = ["admin": Bcrypt.hash("password", cost: 8)]
231 | }
232 | let router = Router(context: BasicAuthRequestContext.self)
233 | router.add(middleware: BasicAuthenticator(users: MyUserRepository()))
234 | router.get { _, context -> String in
235 | guard let user = context.identity else {
236 | throw HTTPError(.unauthorized)
237 | }
238 | return user.username
239 | }
240 | let app = Application(responder: router.buildResponder())
241 | try await app.test(.router) { client in
242 | try await client.execute(uri: "/", method: .get, auth: .basic(username: "admin", password: "password")) { response in
243 | let body = try XCTUnwrap(response.body)
244 | XCTAssertEqual(String(buffer: body), "admin")
245 | }
246 | try await client.execute(uri: "/", method: .get, auth: .basic(username: "adam", password: "password")) { response in
247 | XCTAssertEqual(response.status, .unauthorized)
248 | }
249 | }
250 | }
251 |
252 | func testBasicAuthenticatorWithClosure() async throws {
253 | struct User: PasswordAuthenticatable {
254 | let username: String
255 | let passwordHash: String?
256 | }
257 | let users = ["admin": Bcrypt.hash("password", cost: 8)]
258 | let router = Router(context: BasicAuthRequestContext.self)
259 | router.add(
260 | middleware: BasicAuthenticator { username, _ in
261 | users[username].map { User(username: username, passwordHash: $0) }
262 | }
263 | )
264 | router.get { _, context -> String? in
265 | guard let user = context.identity else {
266 | throw HTTPError(.unauthorized)
267 | }
268 | return user.username
269 | }
270 | let app = Application(responder: router.buildResponder())
271 | try await app.test(.router) { client in
272 | try await client.execute(uri: "/", method: .get, auth: .basic(username: "admin", password: "password")) { response in
273 | let body = try XCTUnwrap(response.body)
274 | XCTAssertEqual(String(buffer: body), "admin")
275 | }
276 | try await client.execute(uri: "/", method: .get, auth: .basic(username: "adam", password: "password")) { response in
277 | XCTAssertEqual(response.status, .unauthorized)
278 | }
279 | }
280 | }
281 | }
282 |
--------------------------------------------------------------------------------
/Tests/HummingbirdAuthTests/BcryptTests.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2022 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import Hummingbird
16 | import HummingbirdAuth
17 | import HummingbirdAuthTesting
18 | import HummingbirdBcrypt
19 | import HummingbirdTesting
20 | import NIOPosix
21 | import XCTest
22 |
23 | final class BcryptTests: XCTestCase {
24 | func testBcrypt() {
25 | let hash = Bcrypt.hash("password")
26 | XCTAssert(Bcrypt.verify("password", hash: hash))
27 | }
28 |
29 | func testBcryptFalse() {
30 | let hash = Bcrypt.hash("password")
31 | XCTAssertFalse(Bcrypt.verify("password1", hash: hash))
32 | }
33 |
34 | func testMultipleBcrypt() async throws {
35 | struct VerifyFailError: Error {}
36 |
37 | try await withThrowingTaskGroup(of: Void.self) { group in
38 | for i in 0..<8 {
39 | group.addTask {
40 | let text = "This is a test \(i)"
41 | let hash = Bcrypt.hash(text)
42 | if Bcrypt.verify(text, hash: hash) {
43 | return
44 | } else {
45 | throw VerifyFailError()
46 | }
47 | }
48 | }
49 | try await group.waitForAll()
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Tests/HummingbirdAuthTests/OTPTests.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2021 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import HummingbirdOTP
16 | import XCTest
17 |
18 | final class OTPTests: XCTestCase {
19 | func randomBuffer(size: Int) -> [UInt8] {
20 | var data = [UInt8](repeating: 0, count: size)
21 | data = data.map { _ in UInt8.random(in: 0...255) }
22 | return data
23 | }
24 |
25 | func testHOTP() {
26 | // test against RFC4226 example values https://tools.ietf.org/html/rfc4226#page-32
27 | let secret = "12345678901234567890"
28 | XCTAssertEqual(HOTP(secret: secret).compute(counter: 0), 755_224)
29 | XCTAssertEqual(HOTP(secret: secret).compute(counter: 1), 287_082)
30 | XCTAssertEqual(HOTP(secret: secret).compute(counter: 2), 359_152)
31 | XCTAssertEqual(HOTP(secret: secret).compute(counter: 3), 969_429)
32 | XCTAssertEqual(HOTP(secret: secret).compute(counter: 4), 338_314)
33 | XCTAssertEqual(HOTP(secret: secret).compute(counter: 5), 254_676)
34 | XCTAssertEqual(HOTP(secret: secret).compute(counter: 6), 287_922)
35 | XCTAssertEqual(HOTP(secret: secret).compute(counter: 7), 162_583)
36 | XCTAssertEqual(HOTP(secret: secret).compute(counter: 8), 399_871)
37 | XCTAssertEqual(HOTP(secret: secret).compute(counter: 9), 520_489)
38 | }
39 |
40 | func testTOTP() {
41 | // test against RFC6238 example values https://tools.ietf.org/html/rfc6238#page-15
42 | let secret = "12345678901234567890"
43 |
44 | let dateFormatter = DateFormatter()
45 | dateFormatter.locale = Locale(identifier: "en_US_POSIX")
46 | dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
47 | dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
48 |
49 | XCTAssertEqual(TOTP(secret: secret, length: 8).compute(date: dateFormatter.date(from: "1970-01-01T00:00:59Z")!), 94_287_082)
50 | XCTAssertEqual(TOTP(secret: secret, length: 8).compute(date: dateFormatter.date(from: "2005-03-18T01:58:29Z")!), 7_081_804)
51 | XCTAssertEqual(TOTP(secret: secret, length: 8).compute(date: dateFormatter.date(from: "2005-03-18T01:58:31Z")!), 14_050_471)
52 | XCTAssertEqual(TOTP(secret: secret, length: 8).compute(date: dateFormatter.date(from: "2009-02-13T23:31:30Z")!), 89_005_924)
53 | XCTAssertEqual(TOTP(secret: secret, length: 8).compute(date: dateFormatter.date(from: "2033-05-18T03:33:20Z")!), 69_279_037)
54 | XCTAssertEqual(TOTP(secret: secret, length: 8).compute(date: dateFormatter.date(from: "2603-10-11T11:33:20Z")!), 65_353_130)
55 | }
56 |
57 | func testAuthenticatorURL() {
58 | let secret = "HB12345678901234567890"
59 | let url = TOTP(secret: secret, length: 8).createAuthenticatorURL(label: "TOTP test", issuer: "Hummingbird")
60 | XCTAssertEqual(url, "otpauth://totp/TOTP%20test?secret=JBBDCMRTGQ2TMNZYHEYDCMRTGQ2TMNZYHEYA&issuer=Hummingbird&digits=8")
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Tests/HummingbirdAuthTests/SessionTests.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Hummingbird server framework project
4 | //
5 | // Copyright (c) 2021-2024 the Hummingbird authors
6 | // Licensed under Apache License v2.0
7 | //
8 | // See LICENSE.txt for license information
9 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
10 | //
11 | // SPDX-License-Identifier: Apache-2.0
12 | //
13 | //===----------------------------------------------------------------------===//
14 |
15 | import HummingbirdAuth
16 | import HummingbirdAuthTesting
17 | import HummingbirdTesting
18 | import NIOPosix
19 | import XCTest
20 |
21 | @testable import Hummingbird
22 |
23 | final class SessionTests: XCTestCase {
24 | func testSessionAuthenticator() async throws {
25 | struct User: Sendable {
26 | let name: String
27 | }
28 |
29 | struct TestUserRepository: UserSessionRepository {
30 | static let testSessionId = 89
31 |
32 | func getUser(from id: Int, context: UserRepositoryContext) async throws -> User? {
33 | let user = self.users[id]
34 | return user
35 | }
36 |
37 | let users = [Self.testSessionId: User(name: "Adam")]
38 | }
39 |
40 | let persist = MemoryPersistDriver()
41 |
42 | let router = Router(context: BasicSessionRequestContext.self)
43 | router.addMiddleware {
44 | SessionMiddleware(storage: persist)
45 | }
46 | router.put("session") { _, context -> Response in
47 | context.sessions.setSession(TestUserRepository.testSessionId)
48 | return .init(status: .ok)
49 | }
50 | router.group()
51 | .add(middleware: SessionAuthenticator(users: TestUserRepository()))
52 | .get("session") { _, context -> HTTPResponse.Status in
53 | guard context.identity != nil else {
54 | return .unauthorized
55 | }
56 | return .ok
57 | }
58 | let app = Application(responder: router.buildResponder())
59 |
60 | try await app.test(.router) { client in
61 | let responseCookies = try await client.execute(uri: "/session", method: .put) { response -> String? in
62 | XCTAssertEqual(response.status, .ok)
63 | return response.headers[.setCookie]
64 | }
65 | let cookies = try XCTUnwrap(responseCookies)
66 | try await client.execute(uri: "/session", method: .get, headers: [.cookie: cookies]) { response in
67 | XCTAssertEqual(response.status, .ok)
68 | }
69 | }
70 | }
71 |
72 | func testSessionAuthenticatorClosure() async throws {
73 | struct User: Sendable {
74 | let name: String
75 | }
76 | struct TestSession: Codable {
77 | let userID: String
78 | }
79 | let router = Router(context: BasicSessionRequestContext.self)
80 | let persist = MemoryPersistDriver()
81 | router.addMiddleware {
82 | SessionMiddleware(storage: persist)
83 | }
84 | router.put("session") { _, context -> HTTPResponse.Status in
85 | context.sessions.setSession(.init(userID: "Adam"))
86 | return .ok
87 | }
88 | router.group()
89 | .addMiddleware {
90 | SessionAuthenticator { session, _ -> User? in
91 | User(name: session.userID)
92 | }
93 | }
94 | .get("session") { _, context -> HTTPResponse.Status in
95 | guard context.identity != nil else {
96 | return .unauthorized
97 | }
98 | return .ok
99 | }
100 | let app = Application(responder: router.buildResponder())
101 |
102 | try await app.test(.router) { client in
103 | let responseCookies = try await client.execute(uri: "/session", method: .put) { response -> String? in
104 | XCTAssertEqual(response.status, .ok)
105 | return response.headers[.setCookie]
106 | }
107 | let cookies = try XCTUnwrap(responseCookies)
108 | try await client.execute(uri: "/session", method: .get, headers: [.cookie: cookies]) { response in
109 | XCTAssertEqual(response.status, .ok)
110 | }
111 | }
112 | }
113 |
114 | func testSessionUpdate() async throws {
115 | struct User: Codable, Sendable {
116 | var name: String
117 | }
118 |
119 | let router = Router(context: BasicSessionRequestContext.self)
120 | let persist = MemoryPersistDriver()
121 | router.add(middleware: SessionMiddleware(storage: persist))
122 | router.post("save") { request, context -> HTTPResponse.Status in
123 | guard
124 | let name = request.uri.queryParameters.get("name")
125 | else {
126 | throw HTTPError(.badRequest)
127 | }
128 | context.sessions.setSession(User(name: name), expiresIn: .seconds(600))
129 | return .ok
130 | }
131 | router.post("update") { request, context -> HTTPResponse.Status in
132 | guard let name = request.uri.queryParameters.get("name") else { throw HTTPError(.badRequest) }
133 | context.sessions.withLockedSession { session in
134 | session?.name = name
135 | }
136 | return .ok
137 | }
138 | router.post("updateExpires") { request, context -> HTTPResponse.Status in
139 | guard let name = request.uri.queryParameters.get("name") else { throw HTTPError(.badRequest) }
140 | context.sessions.setSession(.init(name: name), expiresIn: .seconds(600))
141 | return .ok
142 | }
143 | router.get("name") { _, context -> String in
144 | guard let user = context.sessions.session else { throw HTTPError(.unauthorized) }
145 | return user.name
146 | }
147 | let app = Application(responder: router.buildResponder())
148 |
149 | try await app.test(.router) { client in
150 | var cookie = try await client.execute(uri: "/save?name=john", method: .post) { response -> String in
151 | XCTAssertEqual(response.status, .ok)
152 | return try XCTUnwrap(response.headers[.setCookie])
153 | }
154 | try await client.execute(uri: "/update?name=jane", method: .post, headers: [.cookie: cookie]) { response in
155 | XCTAssertEqual(response.status, .ok)
156 | XCTAssertNil(response.headers[.setCookie])
157 | }
158 | // get save username
159 | try await client.execute(uri: "/name", method: .get, headers: [.cookie: cookie]) { response in
160 | XCTAssertEqual(response.status, .ok)
161 | let buffer = try XCTUnwrap(response.body)
162 | XCTAssertEqual(String(buffer: buffer), "jane")
163 | }
164 | cookie = try await client.execute(uri: "/updateExpires?name=joan", method: .post, headers: [.cookie: cookie]) { response in
165 | XCTAssertEqual(response.status, .ok)
166 | // if we update the cookie expiration date a set-cookie header should be returned
167 | let newCookieHeader = try XCTUnwrap(response.headers[.setCookie])
168 | // check we are updating the existing cookie
169 | let cookieCookie = try XCTUnwrap(Cookie(from: cookie[...]))
170 | let newCookie = try XCTUnwrap(Cookie(from: newCookieHeader[...]))
171 | XCTAssertEqual(cookieCookie.value, newCookie.value)
172 | return newCookieHeader
173 | }
174 | // get save username
175 | try await client.execute(uri: "/name", method: .get, headers: [.cookie: cookie]) { response in
176 | XCTAssertEqual(response.status, .ok)
177 | let buffer = try XCTUnwrap(response.body)
178 | XCTAssertEqual(String(buffer: buffer), "joan")
179 | }
180 | }
181 | }
182 |
183 | func testSessionDeletion() async throws {
184 | struct User: Codable, Sendable {
185 | let name: String
186 | }
187 |
188 | let router = Router(context: BasicSessionRequestContext.self)
189 | let persist = MemoryPersistDriver()
190 | router.add(middleware: SessionMiddleware(storage: persist))
191 | router.post("login") { request, context -> HTTPResponse.Status in
192 | guard let name = request.uri.queryParameters.get("name") else { throw HTTPError(.badRequest) }
193 | context.sessions.setSession(User(name: name), expiresIn: .seconds(600))
194 | return .ok
195 | }
196 | router.post("logout") { _, context -> HTTPResponse.Status in
197 | context.sessions.clearSession()
198 | return .ok
199 | }
200 | router.get("name") { _, context -> String in
201 | guard let user = context.sessions.session else { throw HTTPError(.unauthorized) }
202 | return user.name
203 | }
204 | let app = Application(responder: router.buildResponder())
205 |
206 | try await app.test(.router) { client in
207 | let cookies = try await client.execute(uri: "/login?name=john", method: .post) { response -> String? in
208 | XCTAssertEqual(response.status, .ok)
209 | return response.headers[.setCookie]
210 | }
211 | // get username
212 | try await client.execute(uri: "/name", method: .get, headers: cookies.map { [.cookie: $0] } ?? [:]) { response in
213 | XCTAssertEqual(response.status, .ok)
214 | XCTAssertEqual(String(buffer: response.body), "john")
215 | }
216 | let cookies2 = try await client.execute(uri: "/logout", method: .post) { response -> String? in
217 | XCTAssertEqual(response.status, .ok)
218 | return response.headers[.setCookie]
219 | }
220 | // get username
221 | try await client.execute(uri: "/name", method: .get, headers: cookies2.map { [.cookie: $0] } ?? [:]) { response in
222 | XCTAssertEqual(response.status, .unauthorized)
223 | }
224 | }
225 | }
226 |
227 | func testSessionCookieParameters() async throws {
228 | struct User: Codable, Sendable {
229 | var name: String
230 | }
231 |
232 | let router = Router(context: BasicSessionRequestContext.self)
233 | let persist = MemoryPersistDriver()
234 | router.add(
235 | middleware: SessionMiddleware(
236 | storage: persist,
237 | sessionCookieParameters: .init(
238 | name: "TEST_SESSION_COOKIE",
239 | domain: "https://test.com",
240 | path: "/test",
241 | secure: true,
242 | sameSite: .strict
243 | )
244 | )
245 | )
246 | router.post("save") { request, context -> HTTPResponse.Status in
247 | guard
248 | let name = request.uri.queryParameters.get("name")
249 | else {
250 | throw HTTPError(.badRequest)
251 | }
252 | context.sessions.setSession(User(name: name), expiresIn: .seconds(600))
253 | return .ok
254 | }
255 | let app = Application(responder: router.buildResponder())
256 |
257 | try await app.test(.router) { client in
258 | try await client.execute(uri: "/save?name=john", method: .post) { response in
259 | XCTAssertEqual(response.status, .ok)
260 | let setCookieHeader = try XCTUnwrap(response.headers[.setCookie])
261 | let cookie = try XCTUnwrap(Cookie(from: setCookieHeader[...]))
262 | XCTAssertEqual(cookie.name, "TEST_SESSION_COOKIE")
263 | XCTAssertEqual(cookie.domain, "https://test.com")
264 | XCTAssertEqual(cookie.path, "/test")
265 | XCTAssertEqual(cookie.secure, true)
266 | XCTAssertEqual(cookie.sameSite, .strict)
267 | }
268 | }
269 | }
270 |
271 | /// Save session as one type and retrieve as another.
272 | func testInvalidSession() async throws {
273 | struct User: Codable, Sendable {
274 | let name: String
275 | }
276 |
277 | let router = Router(context: BasicSessionRequestContext.self)
278 | let persist = MemoryPersistDriver()
279 | let sessionStorage = SessionStorage(persist)
280 | let cookie = try await sessionStorage.save(session: 1, expiresIn: .seconds(60))
281 | router.add(middleware: SessionMiddleware(storage: persist))
282 | router.post("test") { _, context in
283 | context.sessions.session?.description
284 | }
285 | let app = Application(responder: router.buildResponder())
286 |
287 | try await app.test(.router) { client in
288 | try await client.execute(uri: "/test", method: .post, headers: [.cookie: cookie.description]) { response in
289 | XCTAssertEqual(response.status, .noContent)
290 | let setCookieHeader = try XCTUnwrap(response.headers[.setCookie])
291 | let cookie = Cookie(from: setCookieHeader[...])
292 | let expires = try XCTUnwrap(cookie?.expires)
293 | XCTAssertLessThanOrEqual(expires, .now)
294 | }
295 | }
296 | }
297 | }
298 |
--------------------------------------------------------------------------------
/scripts/validate.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | ##===----------------------------------------------------------------------===##
3 | ##
4 | ## This source file is part of the Hummingbird server framework project
5 | ##
6 | ## Copyright (c) 2021-2024 the Hummingbird authors
7 | ## Licensed under Apache License v2.0
8 | ##
9 | ## See LICENSE.txt for license information
10 | ## See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
11 | ##
12 | ## SPDX-License-Identifier: Apache-2.0
13 | ##
14 | ##===----------------------------------------------------------------------===##
15 | ##===----------------------------------------------------------------------===##
16 | ##
17 | ## This source file is part of the SwiftNIO open source project
18 | ##
19 | ## Copyright (c) 2017-2019 Apple Inc. and the SwiftNIO project authors
20 | ## Licensed under Apache License v2.0
21 | ##
22 | ## See LICENSE.txt for license information
23 | ## See CONTRIBUTORS.txt for the list of SwiftNIO project authors
24 | ##
25 | ## SPDX-License-Identifier: Apache-2.0
26 | ##
27 | ##===----------------------------------------------------------------------===##
28 |
29 | SWIFT_FORMAT_VERSION=0.53.10
30 |
31 | set -eu
32 | here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
33 |
34 | function replace_acceptable_years() {
35 | # this needs to replace all acceptable forms with 'YEARS'
36 | sed -e 's/20[12][0-9]-20[12][0-9]/YEARS/' -e 's/20[12][0-9]/YEARS/' -e '/^#!/ d'
37 | }
38 |
39 | printf "=> Checking format... "
40 | FIRST_OUT="$(git status --porcelain)"
41 | git ls-files -z '*.swift' | xargs -0 swift format format --parallel --in-place
42 | git diff --exit-code '*.swift'
43 |
44 | SECOND_OUT="$(git status --porcelain)"
45 | if [[ "$FIRST_OUT" != "$SECOND_OUT" ]]; then
46 | printf "\033[0;31mformatting issues!\033[0m\n"
47 | git --no-pager diff
48 | exit 1
49 | else
50 | printf "\033[0;32mokay.\033[0m\n"
51 | fi
52 | printf "=> Checking license headers... "
53 | tmp=$(mktemp /tmp/.soto-core-sanity_XXXXXX)
54 |
55 | exit 0
56 |
57 | for language in swift-or-c; do
58 | declare -a matching_files
59 | declare -a exceptions
60 | expections=( )
61 | matching_files=( -name '*' )
62 | case "$language" in
63 | swift-or-c)
64 | exceptions=( -path '*/Benchmarks/.build/*' -o -name Package.swift)
65 | matching_files=( -name '*.swift' -o -name '*.c' -o -name '*.h' )
66 | cat > "$tmp" <<"EOF"
67 | //===----------------------------------------------------------------------===//
68 | //
69 | // This source file is part of the Hummingbird server framework project
70 | //
71 | // Copyright (c) YEARS the Hummingbird authors
72 | // Licensed under Apache License v2.0
73 | //
74 | // See LICENSE.txt for license information
75 | // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
76 | //
77 | // SPDX-License-Identifier: Apache-2.0
78 | //
79 | //===----------------------------------------------------------------------===//
80 | EOF
81 | ;;
82 | bash)
83 | matching_files=( -name '*.sh' )
84 | cat > "$tmp" <<"EOF"
85 | ##===----------------------------------------------------------------------===##
86 | ##
87 | ## This source file is part of the Hummingbird server framework project
88 | ##
89 | ## Copyright (c) YEARS the Hummingbird authors
90 | ## Licensed under Apache License v2.0
91 | ##
92 | ## See LICENSE.txt for license information
93 | ## See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
94 | ##
95 | ## SPDX-License-Identifier: Apache-2.0
96 | ##
97 | ##===----------------------------------------------------------------------===##
98 | EOF
99 | ;;
100 | *)
101 | echo >&2 "ERROR: unknown language '$language'"
102 | ;;
103 | esac
104 |
105 | lines_to_compare=$(cat "$tmp" | wc -l | tr -d " ")
106 | # need to read one more line as we remove the '#!' line
107 | lines_to_read=$(expr "$lines_to_compare" + 1)
108 | expected_sha=$(cat "$tmp" | shasum)
109 |
110 | (
111 | cd "$here/.."
112 | find . \
113 | \( \! -path './.build/*' -a \
114 | \( "${matching_files[@]}" \) -a \
115 | \( \! \( "${exceptions[@]}" \) \) \) | while read line; do
116 | if [[ "$(cat "$line" | head -n $lines_to_read | replace_acceptable_years | head -n $lines_to_compare | shasum)" != "$expected_sha" ]]; then
117 | printf "\033[0;31mmissing headers in file '$line'!\033[0m\n"
118 | diff -u <(cat "$line" | head -n $lines_to_read | replace_acceptable_years | head -n $lines_to_compare) "$tmp"
119 | exit 1
120 | fi
121 | done
122 | printf "\033[0;32mokay.\033[0m\n"
123 | )
124 | done
125 |
126 | rm "$tmp"
127 |
--------------------------------------------------------------------------------