Compare commits
16 Commits
v0.1.0-pre
...
v0.6.0-alp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f24519787b | ||
|
|
d565380435 | ||
|
|
29a2545396 | ||
|
|
b39a65ff74 | ||
|
|
63f5f175ee | ||
|
|
bfad0418ad | ||
|
|
00da053f50 | ||
|
|
2131fe5d36 | ||
|
|
72dbc49c6f | ||
|
|
db4c6bcade | ||
|
|
ca83e86acb | ||
|
|
9f60e9ea9a | ||
|
|
0d61861343 | ||
|
|
597d9cdf7d | ||
|
|
b4a08b17ab | ||
|
|
a30d42ffce |
22
.github/workflows/hacs.yaml
vendored
Normal file
22
.github/workflows/hacs.yaml
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
---
|
||||
name: hacs
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
schedule:
|
||||
- cron: "0 0 * * *"
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: HACS validation
|
||||
uses: hacs/action@22.5.0
|
||||
with:
|
||||
category: "integration"
|
||||
ignore: brands
|
||||
|
||||
17
.github/workflows/hassfest.yaml
vendored
Normal file
17
.github/workflows/hassfest.yaml
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
---
|
||||
name: hassfest
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
schedule:
|
||||
- cron: "0 0 * * *"
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: home-assistant/actions/hassfest@master
|
||||
20
.github/workflows/lint.yaml
vendored
Normal file
20
.github/workflows/lint.yaml
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Lint
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install the latest version of rye
|
||||
uses: eifinger/setup-rye@v4
|
||||
with:
|
||||
enable-cache: true
|
||||
- name: Sync dependencies
|
||||
run: rye sync
|
||||
- name: Lint (pylint/rye lint)
|
||||
run: rye run check
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -68,9 +68,6 @@ docs/_build/
|
||||
# PyBuilder
|
||||
target/
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
|
||||
650
.pylintrc
Normal file
650
.pylintrc
Normal file
@@ -0,0 +1,650 @@
|
||||
[MAIN]
|
||||
|
||||
# Analyse import fallback blocks. This can be used to support both Python 2 and
|
||||
# 3 compatible code, which means that the block might have code that exists
|
||||
# only in one or another interpreter, leading to false positives when analysed.
|
||||
analyse-fallback-blocks=no
|
||||
|
||||
# Clear in-memory caches upon conclusion of linting. Useful if running pylint
|
||||
# in a server-like mode.
|
||||
clear-cache-post-run=no
|
||||
|
||||
# Load and enable all available extensions. Use --list-extensions to see a list
|
||||
# all available extensions.
|
||||
#enable-all-extensions=
|
||||
|
||||
# In error mode, messages with a category besides ERROR or FATAL are
|
||||
# suppressed, and no reports are done by default. Error mode is compatible with
|
||||
# disabling specific errors.
|
||||
#errors-only=
|
||||
|
||||
# Always return a 0 (non-error) status code, even if lint errors are found.
|
||||
# This is primarily useful in continuous integration scripts.
|
||||
#exit-zero=
|
||||
|
||||
# A comma-separated list of package or module names from where C extensions may
|
||||
# be loaded. Extensions are loading into the active Python interpreter and may
|
||||
# run arbitrary code.
|
||||
extension-pkg-allow-list=
|
||||
|
||||
# A comma-separated list of package or module names from where C extensions may
|
||||
# be loaded. Extensions are loading into the active Python interpreter and may
|
||||
# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
|
||||
# for backward compatibility.)
|
||||
extension-pkg-whitelist=
|
||||
|
||||
# Return non-zero exit code if any of these messages/categories are detected,
|
||||
# even if score is above --fail-under value. Syntax same as enable. Messages
|
||||
# specified are enabled, while categories only check already-enabled messages.
|
||||
fail-on=
|
||||
|
||||
# Specify a score threshold under which the program will exit with error.
|
||||
fail-under=10
|
||||
|
||||
# Interpret the stdin as a python script, whose filename needs to be passed as
|
||||
# the module_or_package argument.
|
||||
#from-stdin=
|
||||
|
||||
# Files or directories to be skipped. They should be base names, not paths.
|
||||
ignore=CVS
|
||||
|
||||
# Add files or directories matching the regular expressions patterns to the
|
||||
# ignore-list. The regex matches against paths and can be in Posix or Windows
|
||||
# format. Because '\\' represents the directory delimiter on Windows systems,
|
||||
# it can't be used as an escape character.
|
||||
ignore-paths=
|
||||
|
||||
# Files or directories matching the regular expression patterns are skipped.
|
||||
# The regex matches against base names, not paths. The default value ignores
|
||||
# Emacs file locks
|
||||
ignore-patterns=^\.#
|
||||
|
||||
# List of module names for which member attributes should not be checked and
|
||||
# will not be imported (useful for modules/projects where namespaces are
|
||||
# manipulated during runtime and thus existing member attributes cannot be
|
||||
# deduced by static analysis). It supports qualified module names, as well as
|
||||
# Unix pattern matching.
|
||||
ignored-modules=
|
||||
|
||||
# Python code to execute, usually for sys.path manipulation such as
|
||||
# pygtk.require().
|
||||
#init-hook=
|
||||
|
||||
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
|
||||
# number of processors available to use, and will cap the count on Windows to
|
||||
# avoid hangs.
|
||||
jobs=1
|
||||
|
||||
# Control the amount of potential inferred values when inferring a single
|
||||
# object. This can help the performance when dealing with large functions or
|
||||
# complex, nested conditions.
|
||||
limit-inference-results=100
|
||||
|
||||
# List of plugins (as comma separated values of python module names) to load,
|
||||
# usually to register additional checkers.
|
||||
load-plugins=
|
||||
|
||||
# Pickle collected data for later comparisons.
|
||||
persistent=yes
|
||||
|
||||
# Resolve imports to .pyi stubs if available. May reduce no-member messages and
|
||||
# increase not-an-iterable messages.
|
||||
prefer-stubs=no
|
||||
|
||||
# Minimum Python version to use for version dependent checks. Will default to
|
||||
# the version used to run pylint.
|
||||
py-version=3.13
|
||||
|
||||
# Discover python modules and packages in the file system subtree.
|
||||
recursive=no
|
||||
|
||||
# Add paths to the list of the source roots. Supports globbing patterns. The
|
||||
# source root is an absolute path or a path relative to the current working
|
||||
# directory used to determine a package namespace for modules located under the
|
||||
# source root.
|
||||
source-roots=
|
||||
|
||||
# When enabled, pylint would attempt to guess common misconfiguration and emit
|
||||
# user-friendly hints instead of false-positive error messages.
|
||||
suggestion-mode=yes
|
||||
|
||||
# Allow loading of arbitrary C extensions. Extensions are imported into the
|
||||
# active Python interpreter and may run arbitrary code.
|
||||
unsafe-load-any-extension=no
|
||||
|
||||
# In verbose mode, extra non-checker-related info will be displayed.
|
||||
#verbose=
|
||||
|
||||
|
||||
[BASIC]
|
||||
|
||||
# Naming style matching correct argument names.
|
||||
argument-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct argument names. Overrides argument-
|
||||
# naming-style. If left empty, argument names will be checked with the set
|
||||
# naming style.
|
||||
#argument-rgx=
|
||||
|
||||
# Naming style matching correct attribute names.
|
||||
attr-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct attribute names. Overrides attr-naming-
|
||||
# style. If left empty, attribute names will be checked with the set naming
|
||||
# style.
|
||||
#attr-rgx=
|
||||
|
||||
# Bad variable names which should always be refused, separated by a comma.
|
||||
bad-names=foo,
|
||||
bar,
|
||||
baz,
|
||||
toto,
|
||||
tutu,
|
||||
tata
|
||||
|
||||
# Bad variable names regexes, separated by a comma. If names match any regex,
|
||||
# they will always be refused
|
||||
bad-names-rgxs=
|
||||
|
||||
# Naming style matching correct class attribute names.
|
||||
class-attribute-naming-style=any
|
||||
|
||||
# Regular expression matching correct class attribute names. Overrides class-
|
||||
# attribute-naming-style. If left empty, class attribute names will be checked
|
||||
# with the set naming style.
|
||||
#class-attribute-rgx=
|
||||
|
||||
# Naming style matching correct class constant names.
|
||||
class-const-naming-style=UPPER_CASE
|
||||
|
||||
# Regular expression matching correct class constant names. Overrides class-
|
||||
# const-naming-style. If left empty, class constant names will be checked with
|
||||
# the set naming style.
|
||||
#class-const-rgx=
|
||||
|
||||
# Naming style matching correct class names.
|
||||
class-naming-style=PascalCase
|
||||
|
||||
# Regular expression matching correct class names. Overrides class-naming-
|
||||
# style. If left empty, class names will be checked with the set naming style.
|
||||
#class-rgx=
|
||||
|
||||
# Naming style matching correct constant names.
|
||||
const-naming-style=UPPER_CASE
|
||||
|
||||
# Regular expression matching correct constant names. Overrides const-naming-
|
||||
# style. If left empty, constant names will be checked with the set naming
|
||||
# style.
|
||||
#const-rgx=
|
||||
|
||||
# Minimum line length for functions/classes that require docstrings, shorter
|
||||
# ones are exempt.
|
||||
docstring-min-length=-1
|
||||
|
||||
# Naming style matching correct function names.
|
||||
function-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct function names. Overrides function-
|
||||
# naming-style. If left empty, function names will be checked with the set
|
||||
# naming style.
|
||||
#function-rgx=
|
||||
|
||||
# Good variable names which should always be accepted, separated by a comma.
|
||||
good-names=i,
|
||||
j,
|
||||
k,
|
||||
ex,
|
||||
Run,
|
||||
_
|
||||
|
||||
# Good variable names regexes, separated by a comma. If names match any regex,
|
||||
# they will always be accepted
|
||||
good-names-rgxs=
|
||||
|
||||
# Include a hint for the correct naming format with invalid-name.
|
||||
include-naming-hint=no
|
||||
|
||||
# Naming style matching correct inline iteration names.
|
||||
inlinevar-naming-style=any
|
||||
|
||||
# Regular expression matching correct inline iteration names. Overrides
|
||||
# inlinevar-naming-style. If left empty, inline iteration names will be checked
|
||||
# with the set naming style.
|
||||
#inlinevar-rgx=
|
||||
|
||||
# Naming style matching correct method names.
|
||||
method-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct method names. Overrides method-naming-
|
||||
# style. If left empty, method names will be checked with the set naming style.
|
||||
#method-rgx=
|
||||
|
||||
# Naming style matching correct module names.
|
||||
module-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct module names. Overrides module-naming-
|
||||
# style. If left empty, module names will be checked with the set naming style.
|
||||
#module-rgx=
|
||||
|
||||
# Colon-delimited sets of names that determine each other's naming style when
|
||||
# the name regexes allow several styles.
|
||||
name-group=
|
||||
|
||||
# Regular expression which should only match function or class names that do
|
||||
# not require a docstring.
|
||||
no-docstring-rgx=^_
|
||||
|
||||
# List of decorators that produce properties, such as abc.abstractproperty. Add
|
||||
# to this list to register other decorators that produce valid properties.
|
||||
# These decorators are taken in consideration only for invalid-name.
|
||||
property-classes=abc.abstractproperty
|
||||
|
||||
# Regular expression matching correct type alias names. If left empty, type
|
||||
# alias names will be checked with the set naming style.
|
||||
#typealias-rgx=
|
||||
|
||||
# Regular expression matching correct type variable names. If left empty, type
|
||||
# variable names will be checked with the set naming style.
|
||||
#typevar-rgx=
|
||||
|
||||
# Naming style matching correct variable names.
|
||||
variable-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct variable names. Overrides variable-
|
||||
# naming-style. If left empty, variable names will be checked with the set
|
||||
# naming style.
|
||||
#variable-rgx=
|
||||
|
||||
|
||||
[CLASSES]
|
||||
|
||||
# Warn about protected attribute access inside special methods
|
||||
check-protected-access-in-special-methods=no
|
||||
|
||||
# List of method names used to declare (i.e. assign) instance attributes.
|
||||
defining-attr-methods=__init__,
|
||||
__new__,
|
||||
setUp,
|
||||
asyncSetUp,
|
||||
__post_init__
|
||||
|
||||
# List of member names, which should be excluded from the protected access
|
||||
# warning.
|
||||
exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit
|
||||
|
||||
# List of valid names for the first argument in a class method.
|
||||
valid-classmethod-first-arg=cls
|
||||
|
||||
# List of valid names for the first argument in a metaclass class method.
|
||||
valid-metaclass-classmethod-first-arg=mcs
|
||||
|
||||
|
||||
[DESIGN]
|
||||
|
||||
# List of regular expressions of class ancestor names to ignore when counting
|
||||
# public methods (see R0903)
|
||||
exclude-too-few-public-methods=
|
||||
|
||||
# List of qualified class names to ignore when counting class parents (see
|
||||
# R0901)
|
||||
ignored-parents=
|
||||
|
||||
# Maximum number of arguments for function / method.
|
||||
max-args=5
|
||||
|
||||
# Maximum number of attributes for a class (see R0902).
|
||||
max-attributes=7
|
||||
|
||||
# Maximum number of boolean expressions in an if statement (see R0916).
|
||||
max-bool-expr=5
|
||||
|
||||
# Maximum number of branch for function / method body.
|
||||
max-branches=12
|
||||
|
||||
# Maximum number of locals for function / method body.
|
||||
max-locals=15
|
||||
|
||||
# Maximum number of parents for a class (see R0901).
|
||||
max-parents=7
|
||||
|
||||
# Maximum number of positional arguments for function / method.
|
||||
#max-positional-arguments=5
|
||||
|
||||
# Maximum number of public methods for a class (see R0904).
|
||||
max-public-methods=20
|
||||
|
||||
# Maximum number of return / yield for function / method body.
|
||||
max-returns=6
|
||||
|
||||
# Maximum number of statements in function / method body.
|
||||
max-statements=50
|
||||
|
||||
# Minimum number of public methods for a class (see R0903).
|
||||
min-public-methods=2
|
||||
|
||||
|
||||
[EXCEPTIONS]
|
||||
|
||||
# Exceptions that will emit a warning when caught.
|
||||
overgeneral-exceptions=builtins.BaseException,builtins.Exception
|
||||
|
||||
|
||||
[FORMAT]
|
||||
|
||||
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
|
||||
expected-line-ending-format=
|
||||
|
||||
# Regexp for a line that is allowed to be longer than the limit.
|
||||
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
|
||||
|
||||
# Number of spaces of indent required inside a hanging or continued line.
|
||||
indent-after-paren=4
|
||||
|
||||
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
|
||||
# tab).
|
||||
indent-string=' '
|
||||
|
||||
# Maximum number of characters on a single line.
|
||||
max-line-length=100
|
||||
|
||||
# Maximum number of lines in a module.
|
||||
max-module-lines=1000
|
||||
|
||||
# Allow the body of a class to be on the same line as the declaration if body
|
||||
# contains single statement.
|
||||
single-line-class-stmt=no
|
||||
|
||||
# Allow the body of an if to be on the same line as the test if there is no
|
||||
# else.
|
||||
single-line-if-stmt=no
|
||||
|
||||
|
||||
[IMPORTS]
|
||||
|
||||
# List of modules that can be imported at any level, not just the top level
|
||||
# one.
|
||||
allow-any-import-level=
|
||||
|
||||
# Allow explicit reexports by alias from a package __init__.
|
||||
allow-reexport-from-package=no
|
||||
|
||||
# Allow wildcard imports from modules that define __all__.
|
||||
allow-wildcard-with-all=no
|
||||
|
||||
# Deprecated modules which should not be used, separated by a comma.
|
||||
deprecated-modules=
|
||||
|
||||
# Output a graph (.gv or any supported image format) of external dependencies
|
||||
# to the given file (report RP0402 must not be disabled).
|
||||
ext-import-graph=
|
||||
|
||||
# Output a graph (.gv or any supported image format) of all (i.e. internal and
|
||||
# external) dependencies to the given file (report RP0402 must not be
|
||||
# disabled).
|
||||
import-graph=
|
||||
|
||||
# Output a graph (.gv or any supported image format) of internal dependencies
|
||||
# to the given file (report RP0402 must not be disabled).
|
||||
int-import-graph=
|
||||
|
||||
# Force import order to recognize a module as part of the standard
|
||||
# compatibility libraries.
|
||||
known-standard-library=
|
||||
|
||||
# Force import order to recognize a module as part of a third party library.
|
||||
known-third-party=enchant
|
||||
|
||||
# Couples of modules and preferred modules, separated by a comma.
|
||||
preferred-modules=
|
||||
|
||||
|
||||
[LOGGING]
|
||||
|
||||
# The type of string formatting that logging methods do. `old` means using %
|
||||
# formatting, `new` is for `{}` formatting.
|
||||
logging-format-style=old
|
||||
|
||||
# Logging modules to check that the string format arguments are in logging
|
||||
# function parameter format.
|
||||
logging-modules=logging
|
||||
|
||||
|
||||
[MESSAGES CONTROL]
|
||||
|
||||
# Only show warnings with the listed confidence levels. Leave empty to show
|
||||
# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
|
||||
# UNDEFINED.
|
||||
confidence=HIGH,
|
||||
CONTROL_FLOW,
|
||||
INFERENCE,
|
||||
INFERENCE_FAILURE,
|
||||
UNDEFINED
|
||||
|
||||
# Disable the message, report, category or checker with the given id(s). You
|
||||
# can either give multiple identifiers separated by comma (,) or put this
|
||||
# option multiple times (only on the command line, not in the configuration
|
||||
# file where it should appear only once). You can also use "--disable=all" to
|
||||
# disable everything first and then re-enable specific checks. For example, if
|
||||
# you want to run only the similarities checker, you can use "--disable=all
|
||||
# --enable=similarities". If you want to run only the classes checker, but have
|
||||
# no Warning level messages displayed, use "--disable=all --enable=classes
|
||||
# --disable=W".
|
||||
disable=raw-checker-failed,
|
||||
bad-inline-option,
|
||||
locally-disabled,
|
||||
file-ignored,
|
||||
suppressed-message,
|
||||
useless-suppression,
|
||||
deprecated-pragma,
|
||||
use-symbolic-message-instead,
|
||||
use-implicit-booleaness-not-comparison-to-string,
|
||||
use-implicit-booleaness-not-comparison-to-zero,
|
||||
relative-beyond-top-level,
|
||||
# Allow keeping TODOs in the code
|
||||
fixme
|
||||
|
||||
# Enable the message, report, category or checker with the given id(s). You can
|
||||
# either give multiple identifier separated by comma (,) or put this option
|
||||
# multiple time (only on the command line, not in the configuration file where
|
||||
# it should appear only once). See also the "--disable" option for examples.
|
||||
enable=
|
||||
|
||||
|
||||
[METHOD_ARGS]
|
||||
|
||||
# List of qualified names (i.e., library.method) which require a timeout
|
||||
# parameter e.g. 'requests.api.get,requests.api.post'
|
||||
timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
|
||||
|
||||
|
||||
[MISCELLANEOUS]
|
||||
|
||||
# List of note tags to take in consideration, separated by a comma.
|
||||
notes=FIXME,
|
||||
XXX,
|
||||
TODO
|
||||
|
||||
# Regular expression of note tags to take in consideration.
|
||||
notes-rgx=
|
||||
|
||||
|
||||
[REFACTORING]
|
||||
|
||||
# Maximum number of nested blocks for function / method body
|
||||
max-nested-blocks=5
|
||||
|
||||
# Complete name of functions that never returns. When checking for
|
||||
# inconsistent-return-statements if a never returning function is called then
|
||||
# it will be considered as an explicit return statement and no message will be
|
||||
# printed.
|
||||
never-returning-functions=sys.exit,argparse.parse_error
|
||||
|
||||
# Let 'consider-using-join' be raised when the separator to join on would be
|
||||
# non-empty (resulting in expected fixes of the type: ``"- " + " -
|
||||
# ".join(items)``)
|
||||
suggest-join-with-non-empty-separator=yes
|
||||
|
||||
|
||||
[REPORTS]
|
||||
|
||||
# Python expression which should return a score less than or equal to 10. You
|
||||
# have access to the variables 'fatal', 'error', 'warning', 'refactor',
|
||||
# 'convention', and 'info' which contain the number of messages in each
|
||||
# category, as well as 'statement' which is the total number of statements
|
||||
# analyzed. This score is used by the global evaluation report (RP0004).
|
||||
evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
|
||||
|
||||
# Template used to display messages. This is a python new-style format string
|
||||
# used to format the message information. See doc for all details.
|
||||
msg-template=
|
||||
|
||||
# Set the output format. Available formats are: text, parseable, colorized,
|
||||
# json2 (improved json format), json (old json format) and msvs (visual
|
||||
# studio). You can also give a reporter class, e.g.
|
||||
# mypackage.mymodule.MyReporterClass.
|
||||
#output-format=
|
||||
|
||||
# Tells whether to display a full report or only the messages.
|
||||
reports=no
|
||||
|
||||
# Activate the evaluation score.
|
||||
score=yes
|
||||
|
||||
|
||||
[SIMILARITIES]
|
||||
|
||||
# Comments are removed from the similarity computation
|
||||
ignore-comments=yes
|
||||
|
||||
# Docstrings are removed from the similarity computation
|
||||
ignore-docstrings=yes
|
||||
|
||||
# Imports are removed from the similarity computation
|
||||
ignore-imports=yes
|
||||
|
||||
# Signatures are removed from the similarity computation
|
||||
ignore-signatures=yes
|
||||
|
||||
# Minimum lines number of a similarity.
|
||||
min-similarity-lines=4
|
||||
|
||||
|
||||
[SPELLING]
|
||||
|
||||
# Limits count of emitted suggestions for spelling mistakes.
|
||||
max-spelling-suggestions=4
|
||||
|
||||
# Spelling dictionary name. No available dictionaries : You need to install
|
||||
# both the python package and the system dependency for enchant to work.
|
||||
spelling-dict=
|
||||
|
||||
# List of comma separated words that should be considered directives if they
|
||||
# appear at the beginning of a comment and should not be checked.
|
||||
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
|
||||
|
||||
# List of comma separated words that should not be checked.
|
||||
spelling-ignore-words=
|
||||
|
||||
# A path to a file that contains the private dictionary; one word per line.
|
||||
spelling-private-dict-file=
|
||||
|
||||
# Tells whether to store unknown words to the private dictionary (see the
|
||||
# --spelling-private-dict-file option) instead of raising a message.
|
||||
spelling-store-unknown-words=no
|
||||
|
||||
|
||||
[STRING]
|
||||
|
||||
# This flag controls whether inconsistent-quotes generates a warning when the
|
||||
# character used as a quote delimiter is used inconsistently within a module.
|
||||
check-quote-consistency=no
|
||||
|
||||
# This flag controls whether the implicit-str-concat should generate a warning
|
||||
# on implicit string concatenation in sequences defined over several lines.
|
||||
check-str-concat-over-line-jumps=no
|
||||
|
||||
|
||||
[TYPECHECK]
|
||||
|
||||
# List of decorators that produce context managers, such as
|
||||
# contextlib.contextmanager. Add to this list to register other decorators that
|
||||
# produce valid context managers.
|
||||
contextmanager-decorators=contextlib.contextmanager
|
||||
|
||||
# List of members which are set dynamically and missed by pylint inference
|
||||
# system, and so shouldn't trigger E1101 when accessed. Python regular
|
||||
# expressions are accepted.
|
||||
generated-members=
|
||||
|
||||
# Tells whether to warn about missing members when the owner of the attribute
|
||||
# is inferred to be None.
|
||||
ignore-none=yes
|
||||
|
||||
# This flag controls whether pylint should warn about no-member and similar
|
||||
# checks whenever an opaque object is returned when inferring. The inference
|
||||
# can return multiple potential results while evaluating a Python object, but
|
||||
# some branches might not be evaluated, which results in partial inference. In
|
||||
# that case, it might be useful to still emit no-member and other checks for
|
||||
# the rest of the inferred objects.
|
||||
ignore-on-opaque-inference=yes
|
||||
|
||||
# List of symbolic message names to ignore for Mixin members.
|
||||
ignored-checks-for-mixins=no-member,
|
||||
not-async-context-manager,
|
||||
not-context-manager,
|
||||
attribute-defined-outside-init
|
||||
|
||||
# List of class names for which member attributes should not be checked (useful
|
||||
# for classes with dynamically set attributes). This supports the use of
|
||||
# qualified names.
|
||||
ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace
|
||||
|
||||
# Show a hint with possible names when a member name was not found. The aspect
|
||||
# of finding the hint is based on edit distance.
|
||||
missing-member-hint=yes
|
||||
|
||||
# The minimum edit distance a name should have in order to be considered a
|
||||
# similar match for a missing member name.
|
||||
missing-member-hint-distance=1
|
||||
|
||||
# The total number of similar names that should be taken in consideration when
|
||||
# showing a hint for a missing member.
|
||||
missing-member-max-choices=1
|
||||
|
||||
# Regex pattern to define which classes are considered mixins.
|
||||
mixin-class-rgx=.*[Mm]ixin
|
||||
|
||||
# List of decorators that change the signature of a decorated function.
|
||||
signature-mutators=
|
||||
|
||||
|
||||
[VARIABLES]
|
||||
|
||||
# List of additional names supposed to be defined in builtins. Remember that
|
||||
# you should avoid defining new builtins when possible.
|
||||
additional-builtins=
|
||||
|
||||
# Tells whether unused global variables should be treated as a violation.
|
||||
allow-global-unused-variables=yes
|
||||
|
||||
# List of names allowed to shadow builtins
|
||||
allowed-redefined-builtins=
|
||||
|
||||
# List of strings which can identify a callback function by name. A callback
|
||||
# name must start or end with one of those strings.
|
||||
callbacks=cb_,
|
||||
_cb
|
||||
|
||||
# A regular expression matching the name of dummy variables (i.e. expected to
|
||||
# not be used).
|
||||
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
|
||||
|
||||
# Argument names that match this expression will be ignored.
|
||||
ignored-argument-names=_.*|^ignored_|^unused_
|
||||
|
||||
# Tells whether we should check for unused import in __init__ files.
|
||||
init-import=no
|
||||
|
||||
# List of qualified module names which can have objects that can redefine
|
||||
# builtins.
|
||||
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
|
||||
1
.python-version
Normal file
1
.python-version
Normal file
@@ -0,0 +1 @@
|
||||
3.13.1
|
||||
128
CODE_OF_CONDUCT.md
Normal file
128
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,128 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
contact@christiaangoossens.nl (email).
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
||||
92
CONTRIBUTING.md
Normal file
92
CONTRIBUTING.md
Normal file
@@ -0,0 +1,92 @@
|
||||
# Contribution Guide
|
||||
Contibutions are very welcome!
|
||||
|
||||
## Non-code contributions
|
||||
If you are not a programmer, you can still contribute by:
|
||||
|
||||
- Adding discussion items over at the [Discussions page](https://github.com/christiaangoossens/hass-oidc-auth/discussions) if you have a question, feature idea or a setup you would like to show off.
|
||||
- Helping others in issues and discussion posts.
|
||||
- Voting on polls and providing input.
|
||||
- If you want to, contributing financially through [Github Sponsors](https://github.com/sponsors/christiaangoossens)
|
||||
|
||||
## Code contributions
|
||||
You may also submit Pull Requests (PRs) to add features yourself! You can find a list that we are currently working on below. Please note that workflows will be run on your pull request and a pull request will only be merged when all checks pass and a review has been conducted (together with a manual test).
|
||||
|
||||
### Development
|
||||
This project uses the Rye package manager for development. You can find installation instructions here: https://rye.astral.sh/guide/installation/. Start by installing the dependencies using rye sync and then point your editor towards the environment created in the .venv directory.
|
||||
You can then run Home Assistant and put the `custom_components/auth_oidc` directory in your HA `config` folder.
|
||||
|
||||
### Docker Compose Development Environment
|
||||
You can also use the following Docker Compose configuration to automatically start up the latest HA release with the `auth_oidc` integration:
|
||||
|
||||
```
|
||||
services:
|
||||
homeassistant:
|
||||
container_name: homeassistant
|
||||
image: "ghcr.io/home-assistant/home-assistant:stable"
|
||||
volumes:
|
||||
- ./config:/config
|
||||
- ./custom_components/auth_oidc:/config/custom_components/auth_oidc
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
ports:
|
||||
- 8123:8123
|
||||
```
|
||||
|
||||
# Found a security issue?
|
||||
Please see [SECURITY.md](./SECURITY.md) for more information on how to submit your security issue securely. You can find previously found vulnerablities and their corresponding security advisories at the [Security Advisories page](https://github.com/christiaangoossens/hass-oidc-auth/security/advisories).
|
||||
|
||||
# Roadmap
|
||||
The following features are on the roadmap:
|
||||
|
||||
## Better user experience
|
||||
*Copied from https://github.com/christiaangoossens/hass-oidc-auth/issues/19*
|
||||
|
||||
Current status on the user experience:
|
||||
|
||||
- I cannot change the login screen as all of this is hard coded in the frontend code. So, I am stuck with the title of "Just checking" and without any description or even a title for the input box. Changing this would require a PR on the Home Assistant frontend repository.
|
||||
- If anyone can refactor their code to allow integrations (Auth Providers) to send custom translations to the frontend when sending the form (here: [custom_components/auth_oidc/provider.py, line 302](https://github.com/christiaangoossens/hass-oidc-auth/blob/main/custom_components/auth_oidc/provider.py#L302)), such that I can send custom translation keys for the title (instead of just using the `mfa` version), description and input label, I would be very happy to accept a PR here as well that accomplishes that.
|
||||
- Bonus points if it uses the same translation system you would use for any normal setup/config flow in the UI.
|
||||
- Extra bonus points if we can add a button or link besides it that allows for opening the start of the OIDC flow there too, within the description for instance.
|
||||
|
||||
- I cannot redirect you to the start of the OIDC process yet, both on mobile and on desktop. Whenever [the PR](https://github.com/home-assistant/frontend/pull/23204) gets merged and a Home Assistant version that's includes the PR is released (or planned), I will hopefully be able to get something like that to work on desktop.
|
||||
- It likely will not work on mobile, as the PR that's now approved only does it for desktop, I tested mobile with that code 2 years ago and it didn't work. I will contact someone on the Android team to see if we can make that happen too at some point.
|
||||
- Mobile will need to open the `window.open` call using Android Custom Tab (Android) / SFSafariViewController (iOS) instead of the normal webview. It seems that external links didn't work at all when I tried it.
|
||||
|
||||
PR's that improve the user experience are welcome, but they should be stable and preferably hack as little as possible.
|
||||
|
||||
## Tests
|
||||
The project still needs the following automated tests on every PR:
|
||||
|
||||
- Spin up Home Assistant (both the required version from the `hacs.json` and the latest version) and verify that it starts up with no warnings or errors
|
||||
- Normal pytest unit testing (https://developers.home-assistant.io/docs/development_testing/)
|
||||
- You might be able to re-use some unit tests from the original implementation by @elupus: https://github.com/home-assistant/core/pull/32926 or from it's inspired work by @allenporter: https://github.com/allenporter/home-assistant-openid-auth-provider/tree/main/tests
|
||||
- Integration test that performs an automatic run-through of an entire flow with an example/mocked OIDC provider, either in Python code or using an external tool (such as Playwright)
|
||||
|
||||
Together, these should test the following:
|
||||
- The integration registers correctly without any errors (spin-up test)
|
||||
- The integration works with both the minimum HA version as well as the latest HA version (spin-up test)
|
||||
- Configuration can be set without any errors (unit test)
|
||||
- Configuration has the correct effects (unit test)
|
||||
- Code works correctly on its own (unit test)
|
||||
- Full flow is functional and displays as expected, including integration with an external OIDC provider (integration test)
|
||||
|
||||
Preferably, we run all tests on every PR to make manual testing unnecessary.
|
||||
|
||||
## Better configuration experience
|
||||
As a conclusion to the poll (https://github.com/christiaangoossens/hass-oidc-auth/discussions/6), it seems that the best option would be to keep the current YAML configuration for advanced uses and add a UI configuration for the common providers.
|
||||
|
||||
I planned for the following user flow:
|
||||
|
||||
1. Add integration in the HA UI
|
||||
2. Get config dialog with a selector for which OIDC provider you are using
|
||||
3. Preconfigure claim configuration using the chosen provider
|
||||
4. Have user input client id & discovery URL with an instruction to configure as public client
|
||||
5. (Optionally) allow users to choose confidential client and input client secret
|
||||
6. Check these fields by requesting the discovery, JWKS
|
||||
7. Ask user if they want to enable groups and allow them to input the correct group name for both roles
|
||||
8. (Optionally) allow users to enable user linking, explain the issues to them with leaving it enabled and allow disabling later
|
||||
9. Inform users that advanced options are only available in YAML, such as networking settings or specific claim configurations
|
||||
10. Have the user perform one login to check that all the fields are correct, just as any OAuth2 integration would, preferably using our oidc_provider
|
||||
11. Save the integration and request restart to enable it (if necessary)
|
||||
|
||||
While I welcome adding configuration by UI, it's not at the top of my priority list. Ask me in the PR if you have any other suggestions and don't forget to add tests for this too. Existing YAML configuration should also remain unaffected, whenever possible.
|
||||
1
FUNDING.yml
Normal file
1
FUNDING.yml
Normal file
@@ -0,0 +1 @@
|
||||
github: christiaangoossens
|
||||
127
README.md
127
README.md
@@ -1,70 +1,103 @@
|
||||
# OIDC Auth for Home Assistant
|
||||
<!-- Based on the Best-README-template from https://github.com/christiaangoossens/hass-oidc-auth -->
|
||||
<a id="readme-top"></a>
|
||||
|
||||
<div align="center">
|
||||
|
||||
[![Stargazers][stars-shield]][stars-url]
|
||||
[![Issues][issues-shield]][issues-url]
|
||||
[![Contributors][contributors-shield]][contributors-url]
|
||||
[![Forks][forks-shield]][forks-url]
|
||||
[![MIT License][license-shield]][license-url]
|
||||
|
||||
</div>
|
||||
|
||||
<!-- PROJECT LOGO -->
|
||||
<br />
|
||||
<div align="center">
|
||||
<a href="https://github.com/christiaangoossens/hass-oidc-auth/">
|
||||
<img src="logo.png" alt="Logo" width="80" height="80">
|
||||
</a>
|
||||
|
||||
<h3 align="center">OpenID Connect for Home Assistant</h3>
|
||||
|
||||
<p align="center">
|
||||
OpenID Connect (OIDC) implementation for Home Assistant through a custom component/integration
|
||||
<br />
|
||||
<br />
|
||||
<a href="./docs/usage.md">Usage Guide</a>
|
||||
·
|
||||
<a href="./docs/configuration.md">Configuration Guide</a>
|
||||
·
|
||||
<a href="./CONTRIBUTING.md">Contribution Guide</a>
|
||||
<br />
|
||||
<br />
|
||||
<a href="https://github.com/christiaangoossens/hass-oidc-auth/discussions?discussions_q=is%3Aopen+category%3AAnnouncements+category%3APolls">Announcements & Polls</a>
|
||||
·
|
||||
<a href="https://github.com/christiaangoossens/hass-oidc-auth/issues">Issues</a>
|
||||
·
|
||||
<a href="https://github.com/christiaangoossens/hass-oidc-auth/discussions/categories/q-a">Questions</a>
|
||||
·
|
||||
<a href="https://github.com/christiaangoossens/hass-oidc-auth/discussions/categories/ideas">Feature Requests</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
> [!CAUTION]
|
||||
> This is a pre-alpha release. I give no guarantees about code quality, error handling or security at this stage. Please treat this repo as a proof of concept for now and only use it on development HA installs.
|
||||
> This is an alpha release. I give no guarantees about code quality, error handling or security at this stage. Use at your own risk.
|
||||
|
||||
Provides an OIDC implementation for Home Assistant.
|
||||
Provides an OpenID Connect (OIDC) implementation for Home Assistant through a custom component/integration. Through this integration, you can create an SSO (single-sign-on) environment within your self-hosted application stack / homelab.
|
||||
|
||||
### Background
|
||||
If you would like to read the background/open letter that lead to this component, please see https://community.home-assistant.io/t/open-letter-for-improving-home-assistants-authentication-system-oidc-sso/494223. It is currently one of the most upvoted feature requests for Home Assistant.
|
||||
|
||||
## How to use
|
||||
### Installation
|
||||
## Installation guide
|
||||
|
||||
Add this repository to [HACS](https://hacs.xyz/).
|
||||
1. Add this repository to [HACS](https://hacs.xyz/).
|
||||
|
||||
Update your `configuration.yaml` file with
|
||||
[](https://my.home-assistant.io/redirect/hacs_repository/?owner=christiaangoossens&repository=hass-oidc-auth&category=Integration)
|
||||
|
||||
```yaml
|
||||
auth_oidc:
|
||||
client_id: ""
|
||||
discovery_url: ""
|
||||
```
|
||||
2. Add the YAML configuration that matches your OIDC provider to `configuration.yaml`. See the [Configuration Guide](./docs/configuration.md) for more details or pick your OIDC provider below:
|
||||
|
||||
Register your client with your OIDC Provider (e.g. Authentik/Authelia) as a public client and get the client_id. Then, use the obtained client_id and discovery URLs to fill the fields in `configuration.yaml`.
|
||||
| <img src="https://goauthentik.io/img/icon_top_brand_colour.svg" width="100"> | <img src="https://www.authelia.com/images/branding/logo-cropped.png" width="100"> | <img src="https://github.com/user-attachments/assets/4ceb2708-9f29-4694-b797-be833efce17d" width="100"> |
|
||||
|:-----------------------------------------------------------------------------------------:|:-------------------------------------------------------------------------------------:|:---------------------------------------------------------------------------------------:|
|
||||
| [Authentik](./docs/provider-configurations/authentik.md) | [Authelia](./docs/provider-configurations/authelia.md) | [Pocket ID](./docs/provider-configurations/pocket-id.md) |
|
||||
|
||||
For example:
|
||||
```yaml
|
||||
auth_oidc:
|
||||
client_id: "someValueForTheClientId"
|
||||
discovery_url: "https://example.com/application/o/application/.well-known/openid-configuration"
|
||||
```
|
||||
By default, the integration assumes you configure Home Assistant as a **public client** and thus only specify the `client_id` and no `client_secret`. For example, your configuration might look like:
|
||||
|
||||
Afterwards, restart Home Assistant.
|
||||
```yaml
|
||||
auth_oidc:
|
||||
client_id: "example"
|
||||
discovery_url: "https://example.com/.well-known/openid-configuration"
|
||||
```
|
||||
|
||||
### Login
|
||||
You should now be able to see a second option on your login screen ("OpenID Connect (SSO)"). It provides you with a single input field.
|
||||
When registering Home Assistant at your OIDC provider, use `<your HA URL>/auth/oidc/callback` as the callback URL and select 'public client'. You should now get the `client_id` and `issuer_url` or `discovery_url` to fill in.
|
||||
|
||||
Sadly, the user experience is pretty poor right now. Go to `/auth/oidc/welcome` (for example `https://hass.io/auth/oidc/welcome`, replace the URL with your Home Assistant URL) and follow the prompts provided to login, then copy the code into the input field from before. You should now login automatically with your username from SSO.
|
||||
3. Restart Home Assistant
|
||||
|
||||
> [!TIP]
|
||||
> You can use a different device to login instead. Open the `/auth/oidc/welcome` link on device A and then type the obtained code into the normal HA login on device B (can also be the mobile app) to login.
|
||||
4. Login through the OIDC Welcome URL at `<your HA URL>/auth/oidc/welcome`. You will have to go there manually for now. For example, it might be located at http://homeassistant.local:8123/auth/oidc/welcome.
|
||||
|
||||
## Development
|
||||
This project uses the Rye package manager for development. You can find installation instructions here: https://rye.astral.sh/guide/installation/.
|
||||
Start by installing the dependencies using `rye sync` and then point your editor towards the environment created in the `.venv` directory.
|
||||
More (detailed) usage instructions can be found in the [Usage Guide](./docs/usage.md).
|
||||
|
||||
### Help wanted
|
||||
If you have any tips or would like to contribute, send me a message. You are also welcome to contribute a PR to fix any of the TODOs.
|
||||
## Contributions
|
||||
Contibutions are very welcome! If you program in Python or have worked with Home Assistant integrations before, please try to contribute. A list of requested contributions/future goals is in the [Contribution Guide](./CONTRIBUTING.md).
|
||||
|
||||
Currently, this is a pre-alpha, so I welcome issues but I cannot guarantee I can fix them (at least within a reasonable time). Please turn on watch for this repository to remain updated. When the component is in a beta stage, issues will likely get fixed more frequently.
|
||||
Please see the [Contribution Guide](./CONTRIBUTING.md) for more information.
|
||||
|
||||
### TODOs
|
||||
### Found a security issue?
|
||||
Please see [SECURITY.md](./SECURITY.md) for more information on how to submit your security issue securely. You can find previously found vulnerablities and their corresponding security advisories at the [Security Advisories page](https://github.com/christiaangoossens/hass-oidc-auth/security/advisories).
|
||||
|
||||
- [X] Basic flow
|
||||
- [ ] Improve welcome screen UI, should render a simple centered Tailwind UI instructing users that you should login externally to obtain a code.
|
||||
- [ ] Improve finish screen UI, showing the code clearly with a copy button and instructions to paste it into Home Assistant.
|
||||
- [ ] Implement error handling on top of this proof of concept (discovery, JWKS, OIDC)
|
||||
- [ ] Make id_token claim used for the group (admin/user) configurable
|
||||
- [ ] Make id_token claim used for the username configurable
|
||||
- [ ] Make id_token claim used for the name configurable
|
||||
- [ ] Add instructions on how to deploy this with Authentik & Authelia
|
||||
- [ ] Configure Github Actions to automatically lint and build the package
|
||||
- [ ] Configure Dependabot for automatic updates
|
||||
## License
|
||||
Distributed under the MIT license with no warranty. You are fully liable for configuring this integration correctly to keep your Home Assistant installation secure. Use at your own risk. The full license can be found in [LICENSE.md](./LICENSE.md)
|
||||
|
||||
Currently impossible TODOs (waiting for assistance from HA devs, not possible without forking HA frontend & apps right now):
|
||||
|
||||
- [ ] Update the HA frontend code to allow a redirection to be requested from an auth provider instead of manually opening welcome page
|
||||
- [ ] Implement this redirection logic to open a new tab on desktop
|
||||
- [ ] Implement this redirection logic to open a Android Custom Tab (Android) / SFSafariViewController (iOS), instead of opening the link in the HA webview
|
||||
- [ ] Implement a final redirect back to the main page with the code as a query param instead of showing the finalize page
|
||||
<!-- MARKDOWN LINKS & IMAGES -->
|
||||
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
|
||||
[contributors-shield]: https://img.shields.io/github/contributors/christiaangoossens/hass-oidc-auth.svg?style=for-the-badge
|
||||
[contributors-url]: https://github.com/christiaangoossens/hass-oidc-auth/graphs/contributors
|
||||
[forks-shield]: https://img.shields.io/github/forks/christiaangoossens/hass-oidc-auth.svg?style=for-the-badge
|
||||
[forks-url]: https://github.com/christiaangoossens/hass-oidc-auth/network/members
|
||||
[stars-shield]: https://img.shields.io/github/stars/christiaangoossens/hass-oidc-auth.svg?style=for-the-badge
|
||||
[stars-url]: https://github.com/christiaangoossens/hass-oidc-auth/stargazers
|
||||
[issues-shield]: https://img.shields.io/github/issues/christiaangoossens/hass-oidc-auth.svg?style=for-the-badge
|
||||
[issues-url]: https://github.com/christiaangoossens/hass-oidc-auth/issues
|
||||
[license-shield]: https://img.shields.io/github/license/christiaangoossens/hass-oidc-auth.svg?style=for-the-badge
|
||||
[license-url]: https://github.com/christiaangoossens/hass-oidc-auth/blob/master/LICENSE.txt
|
||||
|
||||
15
SECURITY.md
Normal file
15
SECURITY.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# Reporting Security Issues
|
||||
|
||||
With the nature of the integration, security issues and bugs are taken very seriously. I appreciate your efforts to responsibly disclose your findings and I will acknowledge your finding in the security advisory and release notes of the release that fixes your vulnerability. Together, we will keep the Home Assistant community safe.
|
||||
|
||||
To report a security issue, please use the GitHub Security Advisory ["Report a Vulnerability"](https://github.com/christiaangoossens/hass-oidc-auth/security/advisories/new) tab. **Do not make a public issue for your security vulnerability!**
|
||||
|
||||
I (@christiaangoossens) will review security advisories regularly and send you a response indicating next steps in handling your report. This might include fixing the vulnerability before disclosing its nature, or working together in a private branch on a fix.
|
||||
|
||||
Please note that this repository is maintained on a volunteer basis, I will try to respond quickly, but no guarantees.
|
||||
|
||||
If your bug has to do with a third party package, please have it fixed there first, such that we can include a fixed version in an update of hass-oidc-auth.
|
||||
If you found a security vulnerability in Home Assistant itself, please report it at https://www.home-assistant.io/security/
|
||||
|
||||
## Non qualifying vulnerabities
|
||||
Some vulnerabilities do not qualify for fixing in a security patch. The Home Assistant team has made a list of them over at https://www.home-assistant.io/security/#non-qualifying-vulnerabilities.
|
||||
@@ -1,60 +1,94 @@
|
||||
"""OIDC Integration for Home Assistant."""
|
||||
|
||||
import logging
|
||||
from typing import OrderedDict
|
||||
|
||||
import voluptuous as vol
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
# Import and re-export config schema explictly
|
||||
# pylint: disable=useless-import-alias
|
||||
from .config import (
|
||||
CONFIG_SCHEMA as CONFIG_SCHEMA,
|
||||
DOMAIN,
|
||||
DEFAULT_TITLE,
|
||||
CLIENT_ID,
|
||||
CLIENT_SECRET,
|
||||
DISCOVERY_URL,
|
||||
DISPLAY_NAME,
|
||||
ID_TOKEN_SIGNING_ALGORITHM,
|
||||
GROUPS_SCOPE,
|
||||
FEATURES,
|
||||
CLAIMS,
|
||||
ROLES,
|
||||
NETWORK,
|
||||
FEATURES_INCLUDE_GROUPS_SCOPE,
|
||||
)
|
||||
|
||||
# pylint: enable=useless-import-alias
|
||||
|
||||
from .endpoints.welcome import OIDCWelcomeView
|
||||
from .endpoints.redirect import OIDCRedirectView
|
||||
from .endpoints.finish import OIDCFinishView
|
||||
from .endpoints.callback import OIDCCallbackView
|
||||
|
||||
from .oidc_client import OIDCClient
|
||||
|
||||
DOMAIN = "auth_oidc"
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
from .provider import OpenIDAuthProvider
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema(
|
||||
{
|
||||
DOMAIN: vol.Schema(
|
||||
{
|
||||
vol.Required("client_id"): vol.Coerce(str),
|
||||
vol.Optional("client_secret"): vol.Coerce(str),
|
||||
vol.Required("discovery_url"): vol.Url(),
|
||||
}
|
||||
)
|
||||
},
|
||||
extra=vol.ALLOW_EXTRA,
|
||||
)
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config):
|
||||
"""Add the OIDC Auth Provider to the providers in Home Assistant"""
|
||||
my_config = config[DOMAIN]
|
||||
|
||||
providers = OrderedDict()
|
||||
|
||||
provider = OpenIDAuthProvider(
|
||||
hass,
|
||||
hass.auth._store,
|
||||
config[DOMAIN],
|
||||
)
|
||||
# Use private APIs until there is a real auth platform
|
||||
# pylint: disable=protected-access
|
||||
provider = OpenIDAuthProvider(hass, hass.auth._store, my_config)
|
||||
|
||||
providers[(provider.type, provider.id)] = provider
|
||||
providers.update(hass.auth._providers)
|
||||
hass.auth._providers = providers
|
||||
# pylint: enable=protected-access
|
||||
|
||||
_LOGGER.debug("Added OIDC provider for Home Assistant")
|
||||
_LOGGER.info("Registered OIDC provider")
|
||||
|
||||
# Define some fields
|
||||
discovery_url = config[DOMAIN]["discovery_url"]
|
||||
client_id = config[DOMAIN]["client_id"]
|
||||
scope = "openid profile email"
|
||||
# Set the correct scopes
|
||||
# Always use 'openid' & 'profile' as they are specified in the OIDC spec
|
||||
# All servers should support this
|
||||
scope = "openid profile"
|
||||
|
||||
oidc_client = oidc_client = OIDCClient(discovery_url, client_id, scope)
|
||||
# Include groups if requested (default is to include 'groups'
|
||||
# as a scope for Authelia & Authentik)
|
||||
features_config = my_config.get(FEATURES, {})
|
||||
include_groups_scope = features_config.get(FEATURES_INCLUDE_GROUPS_SCOPE, True)
|
||||
groups_scope = my_config.get(GROUPS_SCOPE, "groups")
|
||||
if include_groups_scope:
|
||||
scope += " " + groups_scope
|
||||
|
||||
hass.http.register_view(OIDCWelcomeView())
|
||||
# Create the OIDC client
|
||||
oidc_client = oidc_client = OIDCClient(
|
||||
hass=hass,
|
||||
discovery_url=my_config.get(DISCOVERY_URL),
|
||||
client_id=my_config.get(CLIENT_ID),
|
||||
scope=scope,
|
||||
client_secret=my_config.get(CLIENT_SECRET),
|
||||
id_token_signing_alg=my_config.get(ID_TOKEN_SIGNING_ALGORITHM),
|
||||
features=my_config.get(FEATURES, {}),
|
||||
claims=my_config.get(CLAIMS, {}),
|
||||
roles=my_config.get(ROLES, {}),
|
||||
network=my_config.get(NETWORK, {}),
|
||||
)
|
||||
|
||||
# Register the views
|
||||
name = config[DOMAIN].get(DISPLAY_NAME, DEFAULT_TITLE)
|
||||
|
||||
hass.http.register_view(OIDCWelcomeView(name))
|
||||
hass.http.register_view(OIDCRedirectView(oidc_client))
|
||||
hass.http.register_view(OIDCCallbackView(oidc_client, provider))
|
||||
hass.http.register_view(OIDCFinishView())
|
||||
|
||||
_LOGGER.info("Registered OIDC views")
|
||||
|
||||
return True
|
||||
|
||||
111
custom_components/auth_oidc/config.py
Normal file
111
custom_components/auth_oidc/config.py
Normal file
@@ -0,0 +1,111 @@
|
||||
"""Config schema and constants."""
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
CLIENT_ID = "client_id"
|
||||
CLIENT_SECRET = "client_secret"
|
||||
DISCOVERY_URL = "discovery_url"
|
||||
DISPLAY_NAME = "display_name"
|
||||
ID_TOKEN_SIGNING_ALGORITHM = "id_token_signing_alg"
|
||||
GROUPS_SCOPE = "groups_scope"
|
||||
FEATURES = "features"
|
||||
FEATURES_AUTOMATIC_USER_LINKING = "automatic_user_linking"
|
||||
FEATURES_AUTOMATIC_PERSON_CREATION = "automatic_person_creation"
|
||||
FEATURES_DISABLE_PKCE = "disable_rfc7636"
|
||||
FEATURES_INCLUDE_GROUPS_SCOPE = "include_groups_scope"
|
||||
CLAIMS = "claims"
|
||||
CLAIMS_DISPLAY_NAME = "display_name"
|
||||
CLAIMS_USERNAME = "username"
|
||||
CLAIMS_GROUPS = "groups"
|
||||
ROLES = "roles"
|
||||
ROLE_ADMINS = "admin"
|
||||
ROLE_USERS = "user"
|
||||
|
||||
NETWORK = "network"
|
||||
NETWORK_TLS_VERIFY = "tls_verify"
|
||||
NETWORK_TLS_CA_PATH = "tls_ca_path"
|
||||
|
||||
DEFAULT_TITLE = "OpenID Connect (SSO)"
|
||||
|
||||
DOMAIN = "auth_oidc"
|
||||
CONFIG_SCHEMA = vol.Schema(
|
||||
{
|
||||
DOMAIN: vol.Schema(
|
||||
{
|
||||
# Required client ID as registered with the OIDC provider
|
||||
vol.Required(CLIENT_ID): vol.Coerce(str),
|
||||
# Optional Client Secret to enable confidential client mode
|
||||
vol.Optional(CLIENT_SECRET): vol.Coerce(str),
|
||||
# Which OIDC well-known URL should we use?
|
||||
vol.Required(DISCOVERY_URL): vol.Coerce(str),
|
||||
# Which name should be shown on the login screens?
|
||||
vol.Optional(DISPLAY_NAME): vol.Coerce(str),
|
||||
# Should we enforce a specific signing algorithm on the id tokens?
|
||||
# Defaults to RS256/RSA-pubkey
|
||||
vol.Optional(ID_TOKEN_SIGNING_ALGORITHM): vol.Coerce(str),
|
||||
# String value to allow changing the groups scope
|
||||
# Defaults to 'groups' which is used by Authelia and Authentik
|
||||
vol.Optional(GROUPS_SCOPE, default="groups"): vol.Coerce(str),
|
||||
# Which features should be enabled/disabled?
|
||||
# Optional, defaults to sane/secure defaults
|
||||
vol.Optional(FEATURES): vol.Schema(
|
||||
{
|
||||
# Automatically links users to the HA user based on OIDC username claim
|
||||
# See provider.py for explanation
|
||||
vol.Optional(FEATURES_AUTOMATIC_USER_LINKING): vol.Coerce(bool),
|
||||
# Automatically creates a person entry for your new OIDC user
|
||||
# See provider.py for explanation
|
||||
vol.Optional(FEATURES_AUTOMATIC_PERSON_CREATION): vol.Coerce(
|
||||
bool
|
||||
),
|
||||
# Feature flag to disable PKCE to support OIDC servers that do not
|
||||
# allow additional parameters and don't support RFC 7636
|
||||
vol.Optional(FEATURES_DISABLE_PKCE): vol.Coerce(bool),
|
||||
# Boolean which activates and deactivates scope 'groups'
|
||||
vol.Optional(
|
||||
FEATURES_INCLUDE_GROUPS_SCOPE, default=True
|
||||
): vol.Coerce(bool),
|
||||
}
|
||||
),
|
||||
# Determine which specific claims will be used from the id_token
|
||||
# Optional, defaults to most common claims
|
||||
vol.Optional(CLAIMS): vol.Schema(
|
||||
{
|
||||
# Which claim should we use to obtain the display name from OIDC?
|
||||
vol.Optional(CLAIMS_DISPLAY_NAME): vol.Coerce(str),
|
||||
# Which claim should we use to obtain the username from OIDC?
|
||||
vol.Optional(CLAIMS_USERNAME): vol.Coerce(str),
|
||||
# Which claim should we use to obtain the group(s) from OIDC?
|
||||
vol.Optional(CLAIMS_GROUPS): vol.Coerce(str),
|
||||
}
|
||||
),
|
||||
# Determine which specific group values will be mapped to which roles
|
||||
# Optional, defaults user = null, admin = 'admins'
|
||||
# If user role is set, users that do not have either will be rejected!
|
||||
vol.Optional(ROLES): vol.Schema(
|
||||
{
|
||||
# Which group name should we use to assign the user role?
|
||||
vol.Optional(ROLE_USERS): vol.Coerce(str),
|
||||
# What group name should we use to assign the admin role?
|
||||
# Defaults to admins
|
||||
vol.Optional(ROLE_ADMINS): vol.Coerce(str),
|
||||
}
|
||||
),
|
||||
# Network options
|
||||
vol.Optional(NETWORK): vol.Schema(
|
||||
{
|
||||
# Verify x509 certificates provided when starting TLS connections
|
||||
vol.Optional(NETWORK_TLS_VERIFY, default=True): vol.Coerce(
|
||||
bool
|
||||
),
|
||||
# Load custom certificate chain for private CAs
|
||||
vol.Optional(NETWORK_TLS_CA_PATH): vol.Coerce(str),
|
||||
}
|
||||
),
|
||||
}
|
||||
)
|
||||
},
|
||||
# Any extra fields should not go into our config right now
|
||||
# You may set them for upgrading etc
|
||||
extra=vol.REMOVE_EXTRA,
|
||||
)
|
||||
@@ -1,12 +1,13 @@
|
||||
from aiohttp import web
|
||||
"""Callback route to return the user to after external OIDC interaction."""
|
||||
|
||||
from homeassistant.components.http import HomeAssistantView
|
||||
import logging
|
||||
from aiohttp import web
|
||||
from ..oidc_client import OIDCClient
|
||||
from ..provider import OpenIDAuthProvider
|
||||
from ..helpers import get_url, get_view
|
||||
|
||||
PATH = "/auth/oidc/callback"
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
class OIDCCallbackView(HomeAssistantView):
|
||||
"""OIDC Plugin Callback View."""
|
||||
@@ -24,26 +25,42 @@ class OIDCCallbackView(HomeAssistantView):
|
||||
async def get(self, request: web.Request) -> web.Response:
|
||||
"""Receive response."""
|
||||
|
||||
_LOGGER.debug("Callback view accessed")
|
||||
|
||||
params = request.rel_url.query
|
||||
code = params.get("code")
|
||||
state = params.get("state")
|
||||
base_uri = str(request.url).split('/auth', 2)[0]
|
||||
|
||||
if not (code and state):
|
||||
return web.Response(
|
||||
headers={"content-type": "text/html"},
|
||||
text="<h1>Error</h1><p>Missing code or state parameter</p>",
|
||||
view_html = await get_view(
|
||||
"error",
|
||||
{
|
||||
"error": "Missing code or state parameter.",
|
||||
},
|
||||
)
|
||||
return web.Response(text=view_html, content_type="text/html")
|
||||
|
||||
user_details = await self.oidc_client.complete_token_flow(base_uri, code, state)
|
||||
redirect_uri = get_url("/auth/oidc/callback")
|
||||
user_details = await self.oidc_client.async_complete_token_flow(
|
||||
redirect_uri, code, state
|
||||
)
|
||||
if user_details is None:
|
||||
return web.Response(
|
||||
headers={"content-type": "text/html"},
|
||||
text="<h1>Error</h1><p>Failed to get user details, see console.</p>",
|
||||
view_html = await get_view(
|
||||
"error",
|
||||
{
|
||||
"error": "Failed to get user details, "
|
||||
+ "see Home Assistant logs for more information.",
|
||||
},
|
||||
)
|
||||
return web.Response(text=view_html, content_type="text/html")
|
||||
|
||||
code = await self.oidc_provider.save_user_info(user_details)
|
||||
if user_details.get("role") == "invalid":
|
||||
view_html = await get_view(
|
||||
"error",
|
||||
{
|
||||
"error": "User is not in the correct group to access Home Assistant, "
|
||||
+ "contact your administrator!",
|
||||
},
|
||||
)
|
||||
return web.Response(text=view_html, content_type="text/html")
|
||||
|
||||
return web.HTTPFound(base_uri + "/auth/oidc/finish?code=" + code)
|
||||
code = await self.oidc_provider.async_save_user_info(user_details)
|
||||
return web.HTTPFound(get_url("/auth/oidc/finish?code=" + code))
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
from aiohttp import web
|
||||
"""Finish route to allow the user to view their code."""
|
||||
|
||||
from homeassistant.components.http import HomeAssistantView
|
||||
import logging
|
||||
from aiohttp import web
|
||||
from ..helpers import get_view
|
||||
|
||||
PATH = "/auth/oidc/finish"
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
class OIDCFinishView(HomeAssistantView):
|
||||
"""OIDC Plugin Finish View."""
|
||||
@@ -14,11 +15,40 @@ class OIDCFinishView(HomeAssistantView):
|
||||
name = "auth:oidc:finish"
|
||||
|
||||
async def get(self, request: web.Request) -> web.Response:
|
||||
"""Show the finish screen to allow the user to view their code."""
|
||||
|
||||
code = request.query.get("code")
|
||||
|
||||
if not code:
|
||||
view_html = await get_view(
|
||||
"error",
|
||||
{"error": "Missing code to show the finish screen."},
|
||||
)
|
||||
return web.Response(text=view_html, content_type="text/html")
|
||||
|
||||
view_html = await get_view("finish", {"code": code})
|
||||
return web.Response(text=view_html, content_type="text/html")
|
||||
|
||||
async def post(self, request: web.Request) -> web.Response:
|
||||
"""Receive response."""
|
||||
|
||||
code = request.query.get("code", "FAIL")
|
||||
# Get code from the message body
|
||||
data = await request.post()
|
||||
code = data.get("code")
|
||||
|
||||
return web.Response(
|
||||
headers={"content-type": "text/html"},
|
||||
text=f"<h1>Done!</h1><p>Your code is: <b>{code}</b></p><p>Please return to the Home Assistant login screen (or your mobile app) and fill in this code into the single login field. It should be visible if you select 'Login with OpenID Connect (SSO)'.</p>",
|
||||
)
|
||||
if not code:
|
||||
return web.Response(text="No code received", status=500)
|
||||
|
||||
# Return redirect to the main page for sign in with a cookie
|
||||
return web.HTTPFound(
|
||||
location="/",
|
||||
headers={
|
||||
# Set a cookie to enable autologin on only the specific path used
|
||||
# for the POST request, with all strict parameters set
|
||||
# This cookie should not be read by any Javascript or any other paths.
|
||||
# It can be really short lifetime as we redirect immediately (5 seconds)
|
||||
"set-cookie": "auth_oidc_code="
|
||||
+ code
|
||||
+ "; Path=/auth/login_flow; SameSite=Strict; HttpOnly; Max-Age=5",
|
||||
},
|
||||
)
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
"""Redirect route to redirect the user to the external OIDC server,
|
||||
can either be linked to directly or accessed through the welcome page."""
|
||||
|
||||
from aiohttp import web
|
||||
from homeassistant.components.http import HomeAssistantView
|
||||
import logging
|
||||
|
||||
from ..oidc_client import OIDCClient
|
||||
from ..helpers import get_url, get_view
|
||||
|
||||
PATH = "/auth/oidc/redirect"
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
class OIDCRedirectView(HomeAssistantView):
|
||||
"""OIDC Plugin Redirect View."""
|
||||
@@ -15,32 +17,24 @@ class OIDCRedirectView(HomeAssistantView):
|
||||
url = PATH
|
||||
name = "auth:oidc:redirect"
|
||||
|
||||
def __init__(
|
||||
self, oidc_client: OIDCClient
|
||||
) -> None:
|
||||
def __init__(self, oidc_client: OIDCClient) -> None:
|
||||
self.oidc_client = oidc_client
|
||||
|
||||
async def get(self, request: web.Request) -> web.Response:
|
||||
async def get(self, _: web.Request) -> web.Response:
|
||||
"""Receive response."""
|
||||
|
||||
_LOGGER.debug("Redirect view accessed")
|
||||
|
||||
base_uri = str(request.url).split('/auth', 2)[0]
|
||||
_LOGGER.debug("Base URI: %s", base_uri)
|
||||
|
||||
auth_url = await self.oidc_client.get_authorization_url(base_uri)
|
||||
_LOGGER.debug("Auth URL: %s", auth_url)
|
||||
redirect_uri = get_url("/auth/oidc/callback")
|
||||
auth_url = await self.oidc_client.async_get_authorization_url(redirect_uri)
|
||||
|
||||
if auth_url:
|
||||
return web.HTTPFound(auth_url)
|
||||
else:
|
||||
return web.Response(
|
||||
headers={"content-type": "text/html"},
|
||||
text="<h1>Plugin is misconfigured, discovery could not be obtained</h1>",
|
||||
|
||||
view_html = await get_view(
|
||||
"error",
|
||||
{"error": "Integration is misconfigured, discovery could not be obtained."},
|
||||
)
|
||||
return web.Response(text=view_html, content_type="text/html")
|
||||
|
||||
async def post(self, request: web.Request) -> web.Response:
|
||||
"""POST"""
|
||||
|
||||
_LOGGER.debug("Redirect POST view accessed")
|
||||
return await self.get(request)
|
||||
return await self.get(request)
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"""Welcome route to show the user the OIDC login button and give instructions."""
|
||||
|
||||
from aiohttp import web
|
||||
from homeassistant.components.http import HomeAssistantView
|
||||
import logging
|
||||
from ..helpers import get_view
|
||||
|
||||
PATH = "/auth/oidc/welcome"
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
class OIDCWelcomeView(HomeAssistantView):
|
||||
"""OIDC Plugin Welcome View."""
|
||||
@@ -13,12 +14,10 @@ class OIDCWelcomeView(HomeAssistantView):
|
||||
url = PATH
|
||||
name = "auth:oidc:welcome"
|
||||
|
||||
async def get(self, request: web.Request) -> web.Response:
|
||||
def __init__(self, name: str) -> None:
|
||||
self.name = name
|
||||
|
||||
async def get(self, _: web.Request) -> web.Response:
|
||||
"""Receive response."""
|
||||
|
||||
_LOGGER.debug("Welcome view accessed")
|
||||
|
||||
return web.Response(
|
||||
headers={"content-type": "text/html"},
|
||||
text="<h1>OIDC Login (beta)</h1><p><a href='/auth/oidc/redirect'>Login with OIDC</a></p>",
|
||||
)
|
||||
view_html = await get_view("welcome", {"name": self.name})
|
||||
return web.Response(text=view_html, content_type="text/html")
|
||||
|
||||
22
custom_components/auth_oidc/helpers.py
Normal file
22
custom_components/auth_oidc/helpers.py
Normal file
@@ -0,0 +1,22 @@
|
||||
"""Helper functions for the integration."""
|
||||
|
||||
from homeassistant.components import http
|
||||
from .views.loader import AsyncTemplateRenderer
|
||||
|
||||
|
||||
def get_url(path: str) -> str:
|
||||
"""Returns the requested path appended to the current request base URL."""
|
||||
if (req := http.current_request.get()) is None:
|
||||
raise RuntimeError("No current request in context")
|
||||
|
||||
base_uri = str(req.url).split("/auth", 2)[0]
|
||||
return f"{base_uri}{path}"
|
||||
|
||||
|
||||
async def get_view(template: str, parameters: dict | None = None) -> str:
|
||||
"""Returns the generated HTML of the requested view."""
|
||||
if parameters is None:
|
||||
parameters = {}
|
||||
|
||||
renderer = AsyncTemplateRenderer()
|
||||
return await renderer.render_template(f"{template}.html", **parameters)
|
||||
@@ -1,14 +1,23 @@
|
||||
{
|
||||
"domain": "auth_oidc",
|
||||
"name": "OIDC Authentication",
|
||||
"documentation": "",
|
||||
"requirements": [],
|
||||
"ssdp": [],
|
||||
"zeroconf": [],
|
||||
"homekit": {},
|
||||
"dependencies": [
|
||||
"auth"
|
||||
"codeowners": [
|
||||
"@christiaangoossens"
|
||||
],
|
||||
"codeowners": ["@christiaangoossens"],
|
||||
"version": "0.1"
|
||||
}
|
||||
"config_flow": false,
|
||||
"dependencies": [
|
||||
"auth",
|
||||
"http"
|
||||
],
|
||||
"documentation": "https://github.com/christiaangoossens/hass-oidc-auth",
|
||||
"integration_type": "service",
|
||||
"iot_class": "calculated",
|
||||
"issue_tracker": "https://github.com/christiaangoossens/hass-oidc-auth/issues",
|
||||
"requirements": [
|
||||
"python-jose>=3.3.0",
|
||||
"aiofiles>=24.1.0",
|
||||
"jinja2>=3.1.4",
|
||||
"bcrypt>=4.2.0"
|
||||
],
|
||||
"version": "0.5.1"
|
||||
}
|
||||
@@ -1,204 +1,463 @@
|
||||
import aiohttp
|
||||
"""OIDC Client class"""
|
||||
|
||||
import urllib.parse
|
||||
import logging
|
||||
import os
|
||||
import base64
|
||||
import hashlib
|
||||
from jose import jwt
|
||||
import ssl
|
||||
from typing import Optional
|
||||
from functools import partial
|
||||
import aiohttp
|
||||
from jose import jwt, jwk
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from jose import jwk, jwt
|
||||
from .types import UserDetails
|
||||
from .config import (
|
||||
FEATURES_DISABLE_PKCE,
|
||||
CLAIMS_DISPLAY_NAME,
|
||||
CLAIMS_USERNAME,
|
||||
CLAIMS_GROUPS,
|
||||
ROLE_ADMINS,
|
||||
ROLE_USERS,
|
||||
NETWORK_TLS_VERIFY,
|
||||
NETWORK_TLS_CA_PATH,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OIDCClientException(Exception):
|
||||
"Raised when the OIDC Client encounters an error"
|
||||
|
||||
|
||||
class OIDCDiscoveryInvalid(OIDCClientException):
|
||||
"Raised when the discovery document is not found, invalid or otherwise malformed."
|
||||
|
||||
|
||||
class OIDCTokenResponseInvalid(OIDCClientException):
|
||||
"Raised when the token request returns invalid."
|
||||
|
||||
|
||||
class OIDCJWKSInvalid(OIDCClientException):
|
||||
"Raised when the JWKS is invalid or cannot be obtained."
|
||||
|
||||
|
||||
class OIDCStateInvalid(OIDCClientException):
|
||||
"Raised when the state for your request cannot be matched against a stored state."
|
||||
|
||||
|
||||
class OIDCIdTokenSigningAlgorithmInvalid(OIDCTokenResponseInvalid):
|
||||
"Raised when the id_token is signed with the wrong algorithm, adjust your config accordingly."
|
||||
|
||||
|
||||
# pylint: disable=too-many-instance-attributes
|
||||
class OIDCClient:
|
||||
"""OIDC Client implementation for Python, including PKCE."""
|
||||
|
||||
# Flows stores the state, code_verifier and nonce of all current flows.
|
||||
flows = {}
|
||||
|
||||
def __init__(self, discovery_url, client_id, scope):
|
||||
# HTTP session to be used
|
||||
http_session: aiohttp.ClientSession = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
discovery_url: str,
|
||||
client_id: str,
|
||||
scope: str,
|
||||
**kwargs: str,
|
||||
):
|
||||
self.hass = hass
|
||||
self.discovery_url = discovery_url
|
||||
self.discovery_document = None
|
||||
self.client_id = client_id
|
||||
self.scope = scope
|
||||
|
||||
async def fetch_discovery_document(self):
|
||||
# Optional parameters
|
||||
self.client_secret = kwargs.get("client_secret")
|
||||
|
||||
# Default id_token_signing_alg to RS256 if not specified
|
||||
self.id_token_signing_alg = kwargs.get("id_token_signing_alg")
|
||||
if self.id_token_signing_alg is None:
|
||||
self.id_token_signing_alg = "RS256"
|
||||
|
||||
features = kwargs.get("features")
|
||||
claims = kwargs.get("claims")
|
||||
roles = kwargs.get("roles")
|
||||
network = kwargs.get("network")
|
||||
|
||||
self.disable_pkce = features.get(FEATURES_DISABLE_PKCE, False)
|
||||
self.display_name_claim = claims.get(CLAIMS_DISPLAY_NAME, "name")
|
||||
self.username_claim = claims.get(CLAIMS_USERNAME, "preferred_username")
|
||||
self.groups_claim = claims.get(CLAIMS_GROUPS, "groups")
|
||||
self.user_role = roles.get(ROLE_USERS, None)
|
||||
self.admin_role = roles.get(ROLE_ADMINS, "admins")
|
||||
self.tls_verify = network.get(NETWORK_TLS_VERIFY, True)
|
||||
self.tls_ca_path = network.get(NETWORK_TLS_CA_PATH)
|
||||
|
||||
def __del__(self):
|
||||
"""Cleanup the HTTP session."""
|
||||
|
||||
# HA never seems to run this, but it's good practice to close the session
|
||||
if self.http_session:
|
||||
_LOGGER.debug("Closing HTTP session")
|
||||
self.http_session.close()
|
||||
|
||||
def _base64url_encode(self, value: str) -> str:
|
||||
"""Uses base64url encoding on a given string"""
|
||||
return base64.urlsafe_b64encode(value).rstrip(b"=").decode("utf-8")
|
||||
|
||||
def _generate_random_url_string(self, length: int = 16) -> str:
|
||||
"""Generates a random URL safe string (base64_url encoded)"""
|
||||
return self._base64url_encode(os.urandom(length))
|
||||
|
||||
async def _get_http_session(self) -> aiohttp.ClientSession:
|
||||
"""Create or get the existing client session with custom networking/TLS options"""
|
||||
if self.http_session is not None:
|
||||
return self.http_session
|
||||
|
||||
_LOGGER.debug(
|
||||
"Creating HTTP session provider with options: "
|
||||
+ "verify certificates: %r, custom CA file: %s",
|
||||
self.tls_verify,
|
||||
self.tls_ca_path,
|
||||
)
|
||||
|
||||
tcp_connector_args = {"verify_ssl": self.tls_verify}
|
||||
|
||||
if self.tls_ca_path:
|
||||
# Move to hass' executor to prevent blocking code inside non-blocking method
|
||||
ssl_context = await self.hass.loop.run_in_executor(
|
||||
None, partial(ssl.create_default_context, cafile=self.tls_ca_path)
|
||||
)
|
||||
tcp_connector_args["ssl"] = ssl_context
|
||||
|
||||
self.http_session = aiohttp.ClientSession(
|
||||
connector=aiohttp.TCPConnector(**tcp_connector_args)
|
||||
)
|
||||
return self.http_session
|
||||
|
||||
async def _fetch_discovery_document(self):
|
||||
"""Fetches discovery document from the given URL."""
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(self.discovery_url) as response:
|
||||
response.raise_for_status()
|
||||
return await response.json()
|
||||
session = await self._get_http_session()
|
||||
|
||||
async with session.get(self.discovery_url) as response:
|
||||
response.raise_for_status()
|
||||
return await response.json()
|
||||
except aiohttp.ClientResponseError as e:
|
||||
if e.status == 404:
|
||||
_LOGGER.warning(f"Error: Discovery document not found at {self.discovery_url}")
|
||||
_LOGGER.warning(
|
||||
"Error: Discovery document not found at %s", self.discovery_url
|
||||
)
|
||||
else:
|
||||
_LOGGER.warning(f"Error: {e.status} - {e.message}")
|
||||
return None
|
||||
|
||||
async def get_authorization_url(self, base_uri):
|
||||
if not hasattr(self, 'discovery_document'):
|
||||
self.discovery_document = await self.fetch_discovery_document()
|
||||
_LOGGER.warning("Error: %s - %s", e.status, e.message)
|
||||
raise OIDCDiscoveryInvalid from e
|
||||
|
||||
if not self.discovery_document:
|
||||
return None
|
||||
|
||||
auth_endpoint = self.discovery_document['authorization_endpoint']
|
||||
|
||||
# Generate the necessary PKCE parameters, nonce & state
|
||||
code_verifier = base64.urlsafe_b64encode(os.urandom(32)).rstrip(b'=').decode('utf-8')
|
||||
code_challenge = base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode('utf-8')).digest()).rstrip(b'=').decode('utf-8')
|
||||
nonce = base64.urlsafe_b64encode(os.urandom(16)).rstrip(b'=').decode('utf-8')
|
||||
state = base64.urlsafe_b64encode(os.urandom(16)).rstrip(b'=').decode('utf-8')
|
||||
|
||||
# Save all of them for later verification
|
||||
self.flows[state] = {
|
||||
'code_verifier': code_verifier,
|
||||
'nonce': nonce
|
||||
}
|
||||
|
||||
# Construct the params
|
||||
query_params = {
|
||||
'response_type': 'code',
|
||||
'client_id': self.client_id,
|
||||
'redirect_uri': base_uri + '/auth/oidc/callback',
|
||||
'scope': self.scope,
|
||||
'state': state,
|
||||
'nonce': nonce,
|
||||
'code_challenge': code_challenge,
|
||||
'code_challenge_method': 'S256',
|
||||
}
|
||||
|
||||
url = f"{auth_endpoint}?{urllib.parse.urlencode(query_params)}"
|
||||
return url
|
||||
|
||||
async def _make_token_request(self, token_endpoint, query_params):
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(token_endpoint, data=query_params) as response:
|
||||
response.raise_for_status()
|
||||
return await response.json()
|
||||
except aiohttp.ClientResponseError as e:
|
||||
response_json = await response.json()
|
||||
_LOGGER.warning(f"Error: {e.status} - {e.message}, Response: {response_json}")
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
async def _get_jwks(self, jwks_uri):
|
||||
"""Fetches JWKS from the given URL."""
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(jwks_uri) as response:
|
||||
response.raise_for_status()
|
||||
return await response.json()
|
||||
session = await self._get_http_session()
|
||||
|
||||
async with session.get(jwks_uri) as response:
|
||||
response.raise_for_status()
|
||||
return await response.json()
|
||||
except aiohttp.ClientResponseError as e:
|
||||
_LOGGER.warning(f"Error fetching JWKS: {e.status} - {e.message}")
|
||||
return None
|
||||
_LOGGER.warning("Error fetching JWKS: %s - %s", e.status, e.message)
|
||||
raise OIDCJWKSInvalid from e
|
||||
|
||||
async def _parse_id_token(self, id_token):
|
||||
# Parse the id token to obtain the relevant details
|
||||
# Use python-jose
|
||||
if not hasattr(self, 'discovery_document'):
|
||||
self.discovery_document = await self.fetch_discovery_document()
|
||||
async def _make_token_request(self, token_endpoint, query_params):
|
||||
"""Performs the token POST call"""
|
||||
try:
|
||||
session = await self._get_http_session()
|
||||
|
||||
if not self.discovery_document:
|
||||
return None
|
||||
|
||||
jwks_uri = self.discovery_document['jwks_uri']
|
||||
async with session.post(token_endpoint, data=query_params) as response:
|
||||
response.raise_for_status()
|
||||
return await response.json()
|
||||
except aiohttp.ClientResponseError as e:
|
||||
if e.status == 400:
|
||||
_LOGGER.warning(
|
||||
"Error: Token could not be obtained (Bad Request), "
|
||||
+ "did you forget the client_secret?"
|
||||
)
|
||||
else:
|
||||
_LOGGER.warning(
|
||||
"Unexpected error exchanging token: %s - %s", e.status, e.message
|
||||
)
|
||||
raise OIDCTokenResponseInvalid from e
|
||||
|
||||
async def _parse_id_token(
|
||||
self, id_token: str, access_token: str | None
|
||||
) -> Optional[dict]:
|
||||
"""Parses the ID token into a dict containing token contents."""
|
||||
if self.discovery_document is None:
|
||||
self.discovery_document = await self._fetch_discovery_document()
|
||||
|
||||
jwks_uri = self.discovery_document["jwks_uri"]
|
||||
jwks_data = await self._get_jwks(jwks_uri)
|
||||
if not jwks_data:
|
||||
return None
|
||||
|
||||
try:
|
||||
# Obtain the id_token header
|
||||
unverified_header = jwt.get_unverified_header(id_token)
|
||||
if not unverified_header:
|
||||
print("Could not parse JWT Header")
|
||||
_LOGGER.warning("Could not get header from received id_token.")
|
||||
return None
|
||||
|
||||
kid = unverified_header.get('kid')
|
||||
if not kid:
|
||||
print("JWT does not have kid (Key ID)")
|
||||
return None
|
||||
# Obtain the signing algorithm from the header of the id_token
|
||||
alg = unverified_header.get("alg")
|
||||
if alg != self.id_token_signing_alg:
|
||||
# Verify that it matches our requested algorithm
|
||||
_LOGGER.warning(
|
||||
"ID Token received signed with the wrong algorithm: %s, expected %s",
|
||||
alg,
|
||||
self.id_token_signing_alg,
|
||||
)
|
||||
raise OIDCIdTokenSigningAlgorithmInvalid()
|
||||
|
||||
# OpenID Connect Core 1.0 Section 3.1.3.7.8
|
||||
# If the JWT alg Header Parameter uses a MAC based algorithm
|
||||
# such as HS256, HS384, or HS512, the octets of the UTF-8 [RFC3629]
|
||||
# representation of the client_secret corresponding to the client_id
|
||||
# contained in the aud (audience) Claim are used as the key to
|
||||
# validate the signature.
|
||||
if alg.startswith("HS"):
|
||||
if not self.client_secret:
|
||||
_LOGGER.warning(
|
||||
"ID Token signed with HMAC algorithm, but no client_secret provided."
|
||||
)
|
||||
raise OIDCIdTokenSigningAlgorithmInvalid()
|
||||
|
||||
# Get the correct key
|
||||
rsa_key = None
|
||||
for key in jwks_data["keys"]:
|
||||
if key["kid"] == kid:
|
||||
rsa_key = key
|
||||
break
|
||||
jwk_obj = jwk.construct(
|
||||
{
|
||||
"kty": "oct",
|
||||
"k": base64.urlsafe_b64encode(
|
||||
self.client_secret.encode()
|
||||
).decode(),
|
||||
"alg": alg,
|
||||
}
|
||||
)
|
||||
else:
|
||||
# TODO: Deal with cases where kid is not specified (just take the first key?)
|
||||
# Obtain the kid (Key ID) from the header of the id_token
|
||||
kid = unverified_header.get("kid")
|
||||
if not kid:
|
||||
_LOGGER.warning("JWT does not have kid (Key ID)")
|
||||
return None
|
||||
|
||||
if not rsa_key:
|
||||
print(f"Could not find matching key with kid:{kid}")
|
||||
return None
|
||||
# Get the correct key
|
||||
signing_key = None
|
||||
for key in jwks_data["keys"]:
|
||||
if key["kid"] == kid:
|
||||
signing_key = key
|
||||
break
|
||||
|
||||
# Construct the JWK
|
||||
jwk_obj = jwk.construct(rsa_key)
|
||||
if not signing_key:
|
||||
_LOGGER.warning("Could not find matching key with kid: %s", kid)
|
||||
return None
|
||||
|
||||
# Construct the JWK from the RSA key
|
||||
jwk_obj = jwk.construct(signing_key)
|
||||
|
||||
# Verify the token
|
||||
decoded_token = jwt.decode(
|
||||
id_token,
|
||||
jwk_obj,
|
||||
algorithms=["RS256"], # Adjust if your algorithm is different
|
||||
# OpenID Connect Core 1.0 Section 3.1.3.7.6
|
||||
# The Client MUST validate the signature of all other ID Tokens
|
||||
# according to JWS [JWS] using the algorithm specified in the JWT
|
||||
# alg Header Parameter.
|
||||
algorithms=[self.id_token_signing_alg],
|
||||
# OpenID Connect Core 1.0 Section 3.1.3.7.3
|
||||
# The Client MUST validate that the aud (audience) Claim contains
|
||||
# its client_id value registered at the Issuer identified by the
|
||||
# iss (issuer) Claim as an audience.
|
||||
audience=self.client_id,
|
||||
issuer=self.discovery_document['issuer'],
|
||||
# OpenID Connect Core 1.0 Section 3.1.3.7.2
|
||||
# The Issuer Identifier for the OpenID Provider MUST exactly
|
||||
# match the value of the iss (issuer) Claim.
|
||||
issuer=self.discovery_document["issuer"],
|
||||
access_token=access_token,
|
||||
options={
|
||||
# Verify everything if present
|
||||
"verify_signature": True,
|
||||
"verify_aud": True,
|
||||
"verify_iat": True,
|
||||
"verify_exp": True,
|
||||
"verify_nbf": True,
|
||||
"verify_iss": True,
|
||||
"verify_sub": True,
|
||||
"verify_jti": True,
|
||||
"verify_at_hash": True,
|
||||
# OpenID Connect Core 1.0 Section 3.1.3.7.3
|
||||
"require_aud": True,
|
||||
# OpenID Connect Core 1.0 Section 3.1.3.7.10
|
||||
"require_iat": True,
|
||||
# OpenID Connect Core 1.0 Section 3.1.3.7.9
|
||||
"require_exp": True,
|
||||
# OpenID Connect Core 1.0 Section 3.1.3.7.2
|
||||
"require_iss": True,
|
||||
# We need the sub as it's used to identify the user
|
||||
"require_sub": True,
|
||||
# Other values, not required.
|
||||
"require_nbf": False,
|
||||
"require_jti": False,
|
||||
"require_at_hash": False,
|
||||
"leeway": 5,
|
||||
},
|
||||
)
|
||||
return decoded_token
|
||||
|
||||
except jwt.JWTError as e:
|
||||
print(f"JWT Verification failed: {e}")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"Unexpected error: {e}")
|
||||
|
||||
return None
|
||||
|
||||
async def complete_token_flow(self, base_uri, code, state):
|
||||
if state not in self.flows:
|
||||
_LOGGER.warning("JWT Verification failed: %s", e)
|
||||
return None
|
||||
|
||||
flow = self.flows[state]
|
||||
code_verifier = flow['code_verifier']
|
||||
async def async_get_authorization_url(self, redirect_uri: str) -> Optional[str]:
|
||||
"""Generates the authorization URL for the OIDC flow."""
|
||||
try:
|
||||
if self.discovery_document is None:
|
||||
self.discovery_document = await self._fetch_discovery_document()
|
||||
|
||||
if not hasattr(self, 'discovery_document'):
|
||||
self.discovery_document = await self.fetch_discovery_document()
|
||||
auth_endpoint = self.discovery_document["authorization_endpoint"]
|
||||
|
||||
if not self.discovery_document:
|
||||
# Generate random nonce & state
|
||||
nonce = self._generate_random_url_string()
|
||||
state = self._generate_random_url_string()
|
||||
|
||||
# Generate PKCE (RFC 7636) parameters
|
||||
code_verifier = self._generate_random_url_string(32)
|
||||
code_challenge = self._base64url_encode(
|
||||
hashlib.sha256(code_verifier.encode("utf-8")).digest()
|
||||
)
|
||||
|
||||
# Save all of them for later verification
|
||||
self.flows[state] = {"code_verifier": code_verifier, "nonce": nonce}
|
||||
|
||||
# Construct the params
|
||||
query_params = {
|
||||
"response_type": "code",
|
||||
"client_id": self.client_id,
|
||||
"redirect_uri": redirect_uri,
|
||||
"scope": self.scope,
|
||||
"state": state,
|
||||
# Nonce is always set in accordance with OpenID Connect Core 1.0
|
||||
"nonce": nonce,
|
||||
}
|
||||
|
||||
# We always want to use PKCE (RFC 7636), unless it's disabled for compatibility.
|
||||
# PKCE is the recommended method of securing the authorization code grant
|
||||
# for public clients as much as possible.
|
||||
# (see https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-11#section-7.5.1)
|
||||
if not self.disable_pkce:
|
||||
query_params["code_challenge"] = code_challenge
|
||||
query_params["code_challenge_method"] = "S256"
|
||||
|
||||
url = f"{auth_endpoint}?{urllib.parse.urlencode(query_params)}"
|
||||
return url
|
||||
except OIDCClientException as e:
|
||||
_LOGGER.warning("Error generating authorization URL: %s", e)
|
||||
return None
|
||||
|
||||
token_endpoint = self.discovery_document['token_endpoint']
|
||||
async def async_complete_token_flow(
|
||||
self, redirect_uri: str, code: str, state: str
|
||||
) -> Optional[UserDetails]:
|
||||
"""Completes the OIDC token flow to obtain a user's details."""
|
||||
|
||||
# Construct the params
|
||||
query_params = {
|
||||
'grant_type': 'authorization_code',
|
||||
'client_id': self.client_id,
|
||||
'code': code,
|
||||
'redirect_uri': base_uri + '/auth/oidc/callback',
|
||||
'code_verifier': code_verifier,
|
||||
}
|
||||
try:
|
||||
if state not in self.flows:
|
||||
raise OIDCStateInvalid
|
||||
|
||||
_LOGGER.debug(f"Token request params: {query_params}")
|
||||
flow = self.flows[state]
|
||||
|
||||
token_response = await self._make_token_request(token_endpoint, query_params)
|
||||
if self.discovery_document is None:
|
||||
self.discovery_document = await self._fetch_discovery_document()
|
||||
|
||||
if not token_response:
|
||||
token_endpoint = self.discovery_document["token_endpoint"]
|
||||
|
||||
# Construct the params
|
||||
query_params = {
|
||||
"grant_type": "authorization_code",
|
||||
"client_id": self.client_id,
|
||||
"code": code,
|
||||
"redirect_uri": redirect_uri,
|
||||
}
|
||||
|
||||
# Send the client secret if we have one
|
||||
if self.client_secret is not None:
|
||||
query_params["client_secret"] = self.client_secret
|
||||
|
||||
# If we disable PKCE, don't send the code verifier
|
||||
if not self.disable_pkce:
|
||||
query_params["code_verifier"] = flow["code_verifier"]
|
||||
|
||||
# Exchange the code for a token
|
||||
token_response = await self._make_token_request(
|
||||
token_endpoint, query_params
|
||||
)
|
||||
|
||||
id_token = token_response.get("id_token")
|
||||
access_token = token_response.get("access_token")
|
||||
|
||||
# Parse the id token to obtain the relevant details
|
||||
# Access token is supplied to check at_hash if present
|
||||
id_token = await self._parse_id_token(id_token, access_token)
|
||||
|
||||
if id_token is None:
|
||||
_LOGGER.warning("ID token could not be parsed!")
|
||||
return None
|
||||
|
||||
# OpenID Connect Core 1.0 Section 3.1.3.7.11
|
||||
# If a nonce value was sent in the Authentication Request,
|
||||
# a nonce Claim MUST be present and its value checked to verify
|
||||
# that it is the same value as the one that was sent in the Authentication Request.
|
||||
if id_token.get("nonce") != flow["nonce"]:
|
||||
_LOGGER.warning("Nonce mismatch!")
|
||||
return None
|
||||
|
||||
# TODO: If the configured claims are not present in id_token, we should fetch userinfo
|
||||
|
||||
# Get and parse groups (to check if it's an array)
|
||||
groups = id_token.get(self.groups_claim, [])
|
||||
if not isinstance(groups, list):
|
||||
_LOGGER.warning("Groups claim is not a list, using empty list instead.")
|
||||
groups = []
|
||||
|
||||
# Assign role if user has the required groups
|
||||
role = "invalid"
|
||||
if self.user_role in groups or self.user_role is None:
|
||||
role = "system-users"
|
||||
|
||||
if self.admin_role in groups:
|
||||
role = "system-admin"
|
||||
|
||||
# Create a user details dict based on the contents of the id_token & userinfo
|
||||
data: UserDetails = {
|
||||
# Subject Identifier. A locally unique and never reassigned identifier within the
|
||||
# Issuer for the End-User, which is intended to be consumed by the Client
|
||||
# Only unique per issuer, so we combine it with the issuer and hash it.
|
||||
# This might allow multiple OIDC providers to be used with this integration.
|
||||
"sub": hashlib.sha256(
|
||||
f"{self.discovery_document['issuer']}.{id_token.get('sub')}".encode(
|
||||
"utf-8"
|
||||
)
|
||||
).hexdigest(),
|
||||
# Display name, configurable
|
||||
"display_name": id_token.get(self.display_name_claim),
|
||||
# Username, configurable
|
||||
"username": id_token.get(self.username_claim),
|
||||
# Role
|
||||
"role": role,
|
||||
}
|
||||
|
||||
# Log which details were obtained for debugging
|
||||
# Also log the original subject identifier such that you can look it up in your provider
|
||||
_LOGGER.debug(
|
||||
"Obtained user details from OIDC provider: %s (issuer subject: %s)",
|
||||
data,
|
||||
id_token.get("sub"),
|
||||
)
|
||||
return data
|
||||
except OIDCClientException as e:
|
||||
_LOGGER.warning("Error completing token flow: %s", e)
|
||||
return None
|
||||
|
||||
access_token = token_response.get('access_token')
|
||||
id_token = token_response.get('id_token')
|
||||
_LOGGER.debug(f"Access Token: {access_token}")
|
||||
_LOGGER.debug(f"ID Token: {id_token}")
|
||||
|
||||
# Parse the id token to obtain the relevant details
|
||||
id_token = await self._parse_id_token(id_token)
|
||||
|
||||
# Verify nonce
|
||||
if id_token.get('nonce') != flow['nonce']:
|
||||
_LOGGER.warning(f"Nonce mismatch!")
|
||||
return None
|
||||
|
||||
return {
|
||||
"name": id_token.get("name"),
|
||||
"email": id_token.get("email"),
|
||||
"preferred_username": id_token.get("preferred_username"),
|
||||
"nickname": id_token.get("nickname"),
|
||||
"groups": id_token.get("groups"),
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
"""OIDC Authentication provider.
|
||||
Allow access to users based on login with an external OpenID Connect Identity Provider (IdP).
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from typing import Dict, Optional
|
||||
import asyncio
|
||||
import bcrypt
|
||||
from homeassistant.auth import EVENT_USER_ADDED
|
||||
from homeassistant.auth.providers import (
|
||||
AUTH_PROVIDERS,
|
||||
AuthProvider,
|
||||
@@ -10,162 +15,328 @@ from homeassistant.auth.providers import (
|
||||
AuthFlowResult,
|
||||
Credentials,
|
||||
UserMeta,
|
||||
User,
|
||||
AuthStore,
|
||||
)
|
||||
from homeassistant.const import CONF_ID, CONF_NAME, CONF_TYPE
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.components import http, person
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
import voluptuous as vol
|
||||
from datetime import datetime, timedelta
|
||||
import random
|
||||
import string
|
||||
from homeassistant.helpers.storage import Store
|
||||
from collections.abc import Mapping
|
||||
|
||||
from .config import (
|
||||
FEATURES,
|
||||
FEATURES_AUTOMATIC_USER_LINKING,
|
||||
FEATURES_AUTOMATIC_PERSON_CREATION,
|
||||
DEFAULT_TITLE,
|
||||
)
|
||||
from .stores.code_store import CodeStore
|
||||
from .types import UserDetails
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
PROVIDER_TYPE = "auth_oidc"
|
||||
HASS_PROVIDER_TYPE = "homeassistant"
|
||||
|
||||
|
||||
class InvalidAuthError(HomeAssistantError):
|
||||
"""Raised when submitting invalid authentication."""
|
||||
|
||||
|
||||
@AUTH_PROVIDERS.register("oidc")
|
||||
class OpenIDAuthProvider(AuthProvider):
|
||||
"""Allow access to users based on login with an external OpenID Connect Identity Provider (IdP)."""
|
||||
|
||||
DEFAULT_TITLE = "OpenID Connect (SSO)"
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initialize the OpenIDAuthProvider."""
|
||||
super().__init__(*args, **kwargs)
|
||||
self._user_meta = {}
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
return "auth_oidc"
|
||||
"""Allow access to users based on login with an external
|
||||
OpenID Connect Identity Provider (IdP)."""
|
||||
|
||||
@property
|
||||
def support_mfa(self) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def __init__(self, hass: HomeAssistant, store: AuthStore, config: dict[str, str]):
|
||||
"""Initialize the OpenIDAuthProvider."""
|
||||
super().__init__(
|
||||
hass,
|
||||
store,
|
||||
{
|
||||
# Currently register as default, might be used when we have multiple OIDC providers
|
||||
CONF_ID: "default",
|
||||
# Name displayed in the UI
|
||||
CONF_NAME: config.get("display_name", DEFAULT_TITLE),
|
||||
# Type
|
||||
CONF_TYPE: PROVIDER_TYPE,
|
||||
},
|
||||
)
|
||||
|
||||
self._user_meta: dict[UserDetails] = {}
|
||||
self._code_store: CodeStore | None = None
|
||||
self._init_lock = asyncio.Lock()
|
||||
|
||||
features = config.get(
|
||||
FEATURES,
|
||||
{},
|
||||
)
|
||||
|
||||
# Link users automatically?
|
||||
# False by default to always make new accounts for OIDC users
|
||||
# Turn this on to migrate from HA accounts to OIDC
|
||||
self.user_linking = features.get(FEATURES_AUTOMATIC_USER_LINKING, False)
|
||||
|
||||
# Create person entries automatically?
|
||||
# True by default to create a person for each new user (just like normal HA)
|
||||
# Turn this off if you don't want OIDC to interfere more than necessary
|
||||
self.create_persons = features.get(FEATURES_AUTOMATIC_PERSON_CREATION, True)
|
||||
|
||||
async def async_initialize(self) -> None:
|
||||
"""Initialize the auth provider."""
|
||||
|
||||
# Init the code store first
|
||||
# Use the same technique as the HomeAssistant auth provider for storage
|
||||
# (/auth/providers/homeassistant.py#L392)
|
||||
async with self._init_lock:
|
||||
if self._code_store is not None:
|
||||
return
|
||||
|
||||
store = CodeStore(self.hass)
|
||||
await store.async_load()
|
||||
self._code_store = store
|
||||
self._user_meta = {}
|
||||
|
||||
# Listen for user creation events
|
||||
self.hass.bus.async_listen(EVENT_USER_ADDED, self.async_user_created)
|
||||
|
||||
async def async_get_subject(self, code: str) -> Optional[str]:
|
||||
"""Retrieve user from the code, return subject and save meta
|
||||
for later use with this provider instance."""
|
||||
if self._code_store is None:
|
||||
await self.async_initialize()
|
||||
assert self._code_store is not None
|
||||
|
||||
user_data = await self._code_store.receive_userinfo_for_code(code)
|
||||
if user_data is None:
|
||||
return None
|
||||
|
||||
sub = user_data["sub"]
|
||||
self._user_meta[sub] = user_data
|
||||
return sub
|
||||
|
||||
async def async_save_user_info(self, user_info: dict[str, dict | str]) -> str:
|
||||
"""Save user info and return a code."""
|
||||
if self._code_store is None:
|
||||
await self.async_initialize()
|
||||
assert self._code_store is not None
|
||||
|
||||
return await self._code_store.async_generate_code_for_userinfo(user_info)
|
||||
|
||||
async def _async_find_user_by_username(self, username: str) -> Optional[User]:
|
||||
"""Find a user by username."""
|
||||
users = await self.store.async_get_users()
|
||||
for user in users:
|
||||
# System generated users don't have usernames and aren't our target here
|
||||
if user.system_generated:
|
||||
continue
|
||||
|
||||
# Check if we have a homeassistant credential with the provided username
|
||||
for credential in user.credentials:
|
||||
if (
|
||||
credential.auth_provider_type == HASS_PROVIDER_TYPE
|
||||
and credential.data.get("username") == username
|
||||
):
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
# ====
|
||||
# Handler for user created and related functions (person creation)
|
||||
# ====
|
||||
|
||||
@callback
|
||||
async def async_user_created(self, event) -> None:
|
||||
"""Handle the user created event."""
|
||||
user_id = event.data["user_id"]
|
||||
user = await self.store.async_get_user(user_id)
|
||||
|
||||
# Get the first credential, if it's not ours, return
|
||||
if not user.credentials or len(user.credentials) == 0:
|
||||
return
|
||||
|
||||
credential = user.credentials[0]
|
||||
if not (
|
||||
credential.auth_provider_type == self.type
|
||||
and credential.auth_provider_id == self.id
|
||||
):
|
||||
# Not mine, return
|
||||
return
|
||||
|
||||
# Audit log the user creation
|
||||
_LOGGER.info(
|
||||
"User was created for first OIDC sign in: %s from subject %s",
|
||||
user.id,
|
||||
credential.data["sub"],
|
||||
)
|
||||
|
||||
# If person creation is enabled, add a person for this user
|
||||
if self.create_persons:
|
||||
user_meta = await self.async_user_meta_for_credentials(credential)
|
||||
await self.async_create_person(user, user_meta.name)
|
||||
|
||||
async def async_create_person(self, user: User, name: str) -> None:
|
||||
"""Create a person for the user."""
|
||||
_LOGGER.info("Automatically creating person for new user %s", user.id)
|
||||
|
||||
# Create a person for the user
|
||||
try:
|
||||
await person.async_create_person(
|
||||
hass=self.hass,
|
||||
name=name,
|
||||
user_id=user.id,
|
||||
)
|
||||
# Catch all, we don't want to fail here
|
||||
# pylint: disable=broad-exception-caught
|
||||
except Exception:
|
||||
_LOGGER.warning(
|
||||
"Requested automatic person creation, but person creation failed."
|
||||
)
|
||||
# pylint: enable=broad-exception-caught
|
||||
|
||||
# ====
|
||||
# Required functions for Home Assistant Auth Providers
|
||||
# ====
|
||||
|
||||
async def async_login_flow(self, context: Optional[Dict]) -> LoginFlow:
|
||||
"""Return a flow to login."""
|
||||
return OpenIdLoginFlow(self)
|
||||
|
||||
|
||||
async def async_get_or_create_credentials(
|
||||
self, flow_result: Mapping[str, str]
|
||||
self, flow_result: dict[str, str]
|
||||
) -> Credentials:
|
||||
"""Get credentials based on the flow result."""
|
||||
username = flow_result["username"]
|
||||
sub = flow_result["sub"]
|
||||
meta = self._user_meta.get(sub)
|
||||
|
||||
# Audit logging for the login that is about to occur
|
||||
_LOGGER.info(
|
||||
"Logged in user through OIDC: %s, %s", meta["sub"], meta["display_name"]
|
||||
)
|
||||
|
||||
# Iterate over previously created credentials to find one with the same sub
|
||||
for credential in await self.async_credentials():
|
||||
if credential.data["username"] == username:
|
||||
# When logging in again, use the subject to check if the credential exist
|
||||
# OpenID spec says that sub is the only claim we can rely on, as username
|
||||
# might change over time.
|
||||
if credential.data.get("sub") == sub:
|
||||
return credential
|
||||
|
||||
# Create new credentials.
|
||||
return self.async_create_credentials({"username": username})
|
||||
# If no credential was found, create a new one
|
||||
# Username cannot be supplied here as it won't be shown by Home Assistant regardless
|
||||
# Source: homeassistant/components/config/auth.py, line 162
|
||||
credential = self.async_create_credentials({"sub": sub})
|
||||
|
||||
# If we have user linking enabled, try to link the user here
|
||||
if self.user_linking:
|
||||
user = await self._async_find_user_by_username(meta["username"])
|
||||
if user is not None:
|
||||
_LOGGER.info(
|
||||
"User already exists, adding credential for "
|
||||
+ "OIDC to existing user with username '%s'.",
|
||||
meta["username"],
|
||||
)
|
||||
|
||||
# Link the credential to the existing user
|
||||
# Will set the credential isNew = false
|
||||
await self.store.async_link_user(user, credential)
|
||||
|
||||
# If the credential is new, HA will automatically create a new user for us
|
||||
return credential
|
||||
|
||||
async def async_user_meta_for_credentials(
|
||||
self, credentials: Credentials
|
||||
) -> UserMeta:
|
||||
"""Return extra user metadata for credentials.
|
||||
|
||||
Currently, supports name, group and local_only.
|
||||
Currently, supports name, is_active, group and local_only.
|
||||
"""
|
||||
meta = self._user_meta.get(credentials.data["username"], {})
|
||||
groups = meta.get("groups", [])
|
||||
|
||||
group = "system-admin" if "admins" in groups else "system-users"
|
||||
sub = credentials.data["sub"]
|
||||
meta = self._user_meta.get(sub, {})
|
||||
|
||||
role = meta.get("role")
|
||||
return UserMeta(
|
||||
name=meta.get("name"),
|
||||
name=meta.get("display_name"),
|
||||
is_active=True,
|
||||
group=group,
|
||||
local_only="true",
|
||||
group=role,
|
||||
local_only=False,
|
||||
)
|
||||
|
||||
async def save_user_info(self, user_info: dict) -> str:
|
||||
"""Save user info during login."""
|
||||
_LOGGER.info("User info to be saved: %s", user_info)
|
||||
|
||||
code = self._generate_code()
|
||||
expiration = datetime.utcnow() + timedelta(minutes=5)
|
||||
user_data = {
|
||||
"user_info": user_info,
|
||||
"code": code,
|
||||
"expiration": expiration.isoformat()
|
||||
}
|
||||
|
||||
await self._save_to_db(self._get_code_key(code), user_data)
|
||||
return code
|
||||
|
||||
async def async_retrieve_username(self, code: str) -> Optional[dict]:
|
||||
"""Retrieve user info based on the code."""
|
||||
user_data = await self._get_from_db(self._get_code_key(code))
|
||||
await self._wipe_from_db(self._get_code_key(code))
|
||||
|
||||
if user_data and datetime.fromisoformat(user_data["expiration"]) > datetime.utcnow():
|
||||
username = user_data["user_info"]["preferred_username"]
|
||||
self._user_meta[username] = user_data["user_info"]
|
||||
return username
|
||||
return None
|
||||
|
||||
def _generate_code(self) -> str:
|
||||
"""Generate a random six-digit code."""
|
||||
return ''.join(random.choices(string.digits, k=6))
|
||||
|
||||
def _get_code_key(self, code: str) -> str:
|
||||
return f"provider_oidc_auth_user_{code}"
|
||||
|
||||
async def _save_to_db(self, key: str, value: dict) -> None:
|
||||
"""Save key-value data to the Home Assistant storage."""
|
||||
store = Store(self.hass, 1, key)
|
||||
await store.async_save(value)
|
||||
|
||||
async def _get_from_db(self, key: str) -> Optional[dict]:
|
||||
"""Retrieve key-value data from the Home Assistant storage."""
|
||||
store = Store(self.hass, 1, key)
|
||||
return await store.async_load()
|
||||
|
||||
async def _wipe_from_db(self, key: str) -> None:
|
||||
"""Delete key-value data from the Home Assistant storage."""
|
||||
store = Store(self.hass, 1, key)
|
||||
return await store.async_remove()
|
||||
|
||||
|
||||
class OpenIdLoginFlow(LoginFlow):
|
||||
"""Handler for the login flow."""
|
||||
|
||||
async def _finalize_user(self, code: str) -> AuthFlowResult:
|
||||
# Verify a dummy hash to make it last a bit longer
|
||||
# as security measure (limits the amount of attempts you have in 5 min)
|
||||
# Similar to what the HomeAssistant auth provider does
|
||||
dummy = b"$2b$12$CiuFGszHx9eNHxPuQcwBWez4CwDTOcLTX5CbOpV6gef2nYuXkY7BO"
|
||||
bcrypt.checkpw(b"foo", dummy)
|
||||
|
||||
# Actually look up the auth provider after,
|
||||
# this doesn't take a lot of time (regardless of it's in there or not)
|
||||
sub = await self._auth_provider.async_get_subject(code)
|
||||
if sub:
|
||||
return await self.async_finish(
|
||||
{
|
||||
"sub": sub,
|
||||
}
|
||||
)
|
||||
|
||||
raise InvalidAuthError
|
||||
|
||||
def _show_login_form(
|
||||
self, errors: Optional[dict[str, str]] = None
|
||||
) -> AuthFlowResult:
|
||||
if errors is None:
|
||||
errors = {}
|
||||
|
||||
# Show the login form
|
||||
# Abuses the MFA form, as it works better for our usecase
|
||||
# UI suggestions are welcome (make a PR!)
|
||||
return self.async_show_form(
|
||||
step_id="mfa",
|
||||
data_schema=vol.Schema(
|
||||
{
|
||||
vol.Required("code"): str,
|
||||
}
|
||||
),
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
async def async_step_init(
|
||||
self, user_input: dict[str, str] | None = None
|
||||
) -> AuthFlowResult:
|
||||
"""Handle the step of the form."""
|
||||
|
||||
# Show the login form
|
||||
# Currently, this form looks bad because the frontend gives no options to make it look better
|
||||
# We will investigate options to make it look better in the future
|
||||
return self.async_show_form(
|
||||
step_id="mfa",
|
||||
data_schema=vol.Schema(
|
||||
{
|
||||
vol.Required("code"): str,
|
||||
}
|
||||
),
|
||||
errors={},
|
||||
)
|
||||
|
||||
# Try to use the user input first
|
||||
if user_input is not None:
|
||||
try:
|
||||
return await self._finalize_user(user_input["code"])
|
||||
except InvalidAuthError:
|
||||
return self._show_login_form({"base": "invalid_auth"})
|
||||
|
||||
# If not available, check the cookie
|
||||
req = http.current_request.get()
|
||||
code_cookie = req.cookies.get("auth_oidc_code")
|
||||
|
||||
if code_cookie:
|
||||
_LOGGER.debug("Code cookie found on login: %s", code_cookie)
|
||||
try:
|
||||
return await self._finalize_user(code_cookie)
|
||||
except InvalidAuthError:
|
||||
pass
|
||||
|
||||
# If none are available, just show the form
|
||||
return self._show_login_form()
|
||||
|
||||
async def async_step_mfa(
|
||||
self, user_input: dict[str, str] | None = None
|
||||
) -> AuthFlowResult:
|
||||
"""Handle the result of the form."""
|
||||
|
||||
if user_input is None:
|
||||
return self.async_abort(reason="no_code_given")
|
||||
|
||||
# Log
|
||||
_LOGGER.info("User input %s", user_input)
|
||||
_LOGGER.info("Code %s was entered", user_input["code"])
|
||||
|
||||
username = await self._auth_provider.async_retrieve_username(user_input["code"])
|
||||
if username:
|
||||
_LOGGER.info("Logged in user: %s", username)
|
||||
|
||||
return await self.async_finish({
|
||||
"username": username,
|
||||
})
|
||||
|
||||
return self.async_abort(reason="invalid_code")
|
||||
# This is a dummy step function just to use the nicer MFA UI instead
|
||||
return await self.async_step_init(user_input)
|
||||
|
||||
78
custom_components/auth_oidc/stores/code_store.py
Normal file
78
custom_components/auth_oidc/stores/code_store.py
Normal file
@@ -0,0 +1,78 @@
|
||||
"""Code Store, stores the codes and their associated authenticated user temporarily."""
|
||||
|
||||
import random
|
||||
import string
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import cast, Optional
|
||||
from homeassistant.helpers.storage import Store
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from ..types import UserDetails
|
||||
|
||||
STORAGE_VERSION = 1
|
||||
STORAGE_KEY = "auth_provider.auth_oidc.codes"
|
||||
|
||||
|
||||
class CodeStore:
|
||||
"""Holds the codes and associated data"""
|
||||
|
||||
def __init__(self, hass: HomeAssistant) -> None:
|
||||
"""Initialize the user data store."""
|
||||
self.hass = hass
|
||||
self._store = Store[dict[str, UserDetails]](
|
||||
hass, STORAGE_VERSION, STORAGE_KEY, private=True, atomic_writes=True
|
||||
)
|
||||
self._data: dict[str, dict[str, dict | str]] | None = None
|
||||
|
||||
async def async_load(self) -> None:
|
||||
"""Load stored data."""
|
||||
if (data := await self._store.async_load()) is None:
|
||||
data = cast(dict[str, UserDetails], {})
|
||||
self._data = data
|
||||
|
||||
async def async_save(self) -> None:
|
||||
"""Save data."""
|
||||
if self._data is not None:
|
||||
await self._store.async_save(self._data)
|
||||
|
||||
def _generate_code(self) -> str:
|
||||
"""Generate a random six-digit code."""
|
||||
return "".join(random.choices(string.digits, k=6))
|
||||
|
||||
async def async_generate_code_for_userinfo(self, user_info: UserDetails) -> str:
|
||||
"""Generates a one time code and adds it to the database for 5 minutes."""
|
||||
if self._data is None:
|
||||
raise RuntimeError("Data not loaded")
|
||||
|
||||
code = self._generate_code()
|
||||
expiration = datetime.utcnow() + timedelta(minutes=5)
|
||||
|
||||
self._data[code] = {
|
||||
"user_info": user_info,
|
||||
"code": code,
|
||||
"expiration": expiration.isoformat(),
|
||||
}
|
||||
|
||||
await self.async_save()
|
||||
return code
|
||||
|
||||
async def receive_userinfo_for_code(self, code: str) -> Optional[UserDetails]:
|
||||
"""Retrieve user info based on the code."""
|
||||
if self._data is None:
|
||||
raise RuntimeError("Data not loaded")
|
||||
|
||||
user_data = self._data.get(code)
|
||||
|
||||
if user_data:
|
||||
# We should now wipe it from the database, as it's one time use code
|
||||
self._data.pop(code)
|
||||
await self.async_save()
|
||||
|
||||
if (
|
||||
user_data
|
||||
and datetime.fromisoformat(user_data["expiration"]) > datetime.utcnow()
|
||||
):
|
||||
return user_data["user_info"]
|
||||
|
||||
return None
|
||||
18
custom_components/auth_oidc/types.py
Normal file
18
custom_components/auth_oidc/types.py
Normal file
@@ -0,0 +1,18 @@
|
||||
"""Generic data types"""
|
||||
|
||||
# Dict class to give a type to the user details
|
||||
from typing import Literal
|
||||
|
||||
|
||||
class UserDetails(dict):
|
||||
"""User details representation"""
|
||||
|
||||
# User subject, persistent identifier
|
||||
sub: str
|
||||
# Full name of the user for display purposes
|
||||
display_name: str
|
||||
# Preferred username for the user, will be used when first generating the account
|
||||
# or to link the account on first login
|
||||
username: str
|
||||
# Home Assistant role to assign to this user
|
||||
role: Literal["system-admin", "system-users", "invalid"]
|
||||
62
custom_components/auth_oidc/views/loader.py
Normal file
62
custom_components/auth_oidc/views/loader.py
Normal file
@@ -0,0 +1,62 @@
|
||||
"""Jinja2 Async Environment"""
|
||||
|
||||
import logging
|
||||
from os import path
|
||||
from typing import Dict, Any
|
||||
from jinja2 import Environment, DictLoader
|
||||
from aiofiles.os import scandir as async_scandir
|
||||
from aiofiles import open as async_open
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
templates: Dict[str, str] = {}
|
||||
|
||||
|
||||
class AsyncTemplateRenderer:
|
||||
"""An asynchronous template renderer that caches rendered templates."""
|
||||
|
||||
def __init__(self, template_dir: str = None):
|
||||
self.template_dir = template_dir or path.join(
|
||||
path.dirname(path.abspath(__file__)), "templates"
|
||||
)
|
||||
|
||||
async def fetch_templates(self) -> None:
|
||||
"""Fetches all HTML files from the template directory."""
|
||||
templates.clear()
|
||||
|
||||
files = await async_scandir(self.template_dir)
|
||||
|
||||
for file in files:
|
||||
if file.is_dir():
|
||||
continue
|
||||
|
||||
filename = file.name
|
||||
if filename.endswith(".html"):
|
||||
template_path = path.join(self.template_dir, filename)
|
||||
try:
|
||||
_LOGGER.debug("Fetching template %s from disk", filename)
|
||||
async with async_open(
|
||||
template_path, mode="r", encoding="utf-8"
|
||||
) as f:
|
||||
content = await f.read()
|
||||
templates[filename] = content
|
||||
except (OSError, IOError) as e:
|
||||
_LOGGER.warning("Error reading template file %s: %s", filename, e)
|
||||
|
||||
async def render_template(self, template_name: str, **kwargs: Any) -> str:
|
||||
"""Renders a template with the given parameters."""
|
||||
|
||||
if not templates:
|
||||
await (
|
||||
self.fetch_templates()
|
||||
) # If the templates haven't been fetched, fetch them
|
||||
|
||||
if template_name not in templates:
|
||||
raise ValueError(f"Template '{template_name}' not found.")
|
||||
|
||||
env = Environment(loader=DictLoader(templates), enable_async=True)
|
||||
template = env.get_template(template_name)
|
||||
|
||||
# Render template
|
||||
rendered_output = await template.render_async(**kwargs)
|
||||
return rendered_output
|
||||
19
custom_components/auth_oidc/views/templates/base.html
Normal file
19
custom_components/auth_oidc/views/templates/base.html
Normal file
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" class="h-full min-h-full max-h-full">
|
||||
|
||||
<head>
|
||||
{% block head %}
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{% block title %}{% endblock %}</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
{% endblock %}
|
||||
</head>
|
||||
|
||||
<body class="bg-gray-200 flex items-center justify-center h-full">
|
||||
<div class="bg-white p-6 rounded-lg shadow-lg max-w-md">
|
||||
{% block content %}{% endblock %}
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
16
custom_components/auth_oidc/views/templates/error.html
Normal file
16
custom_components/auth_oidc/views/templates/error.html
Normal file
@@ -0,0 +1,16 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Oops!{% endblock %}
|
||||
{% block head %}
|
||||
{{ super() }}
|
||||
{% endblock %}
|
||||
{% block content %}
|
||||
<div class="text-center">
|
||||
<h1 class="text-2xl font-bold mb-4">Login failed.</h1>
|
||||
<p class="mb-4">{{ error }}</p>
|
||||
<div class="my-6">
|
||||
<a href='/auth/oidc/redirect'
|
||||
class="w-full py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75">Try
|
||||
again</a>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
31
custom_components/auth_oidc/views/templates/finish.html
Normal file
31
custom_components/auth_oidc/views/templates/finish.html
Normal file
@@ -0,0 +1,31 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Logged in!{% endblock %}
|
||||
{% block head %}
|
||||
{{ super() }}
|
||||
{% endblock %}
|
||||
{% block content %}
|
||||
<div class="text-center">
|
||||
<div class="my-6">
|
||||
<h2 class="text-xl font-semibold mb-6 text-gray-800">I want to login to this browser</h2>
|
||||
<form method="post">
|
||||
<input type="hidden" name="code" value="{{ code }}">
|
||||
<button type="submit"
|
||||
class="w-full py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75">
|
||||
Login to Home Assistant in this browser
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<hr class="my-12">
|
||||
|
||||
<div class="my-6">
|
||||
<h2 class="text-xl font-semibold mb-4 text-gray-800">I am on a mobile device</h2>
|
||||
<p class="mb-4">Your one-time code is: <b class="text-blue-600 text-xl">{{ code }}</b></p>
|
||||
<p class="mb-4 text-sm">You have 5 minutes to use this code on any device.<br />The code can only
|
||||
be used once.</p>
|
||||
<p class="mb-4 text-sm">Please type the code into your app manually. If you don't see a code input, select
|
||||
'Login with
|
||||
OpenID Connect (SSO)' first.</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
55
custom_components/auth_oidc/views/templates/welcome.html
Normal file
55
custom_components/auth_oidc/views/templates/welcome.html
Normal file
@@ -0,0 +1,55 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}OIDC Login{% endblock %}
|
||||
{% block head %}
|
||||
{{ super() }}
|
||||
{% endblock %}
|
||||
{% block content %}
|
||||
<div class="text-center">
|
||||
<div id="signed-in" class="bg-blue-100 border border-blue-400 text-blue-700 px-4 py-3 rounded relative mb-8 hidden"
|
||||
role="alert">
|
||||
<p>You seem to be logged in already.</p>
|
||||
<p><a href="/" class="text-blue-600 hover:underline hover:text-blue-700 font-bold">Open the Home Assistant
|
||||
dashboard</a></p>
|
||||
</div>
|
||||
|
||||
<h1 class="text-2xl font-bold mb-4">Home Assistant</h1>
|
||||
<p class="mb-4">You have been invited to login to Home Assistant.<br />Start the login process below.</p>
|
||||
|
||||
<div>
|
||||
<button id="oidc-login-btn"
|
||||
class="w-full py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75">
|
||||
Login with {{ name }}
|
||||
</button>
|
||||
|
||||
<div role="status" id="loader" class="items-center justify-center flex hidden">
|
||||
<svg aria-hidden="true" class="w-10 h-10 text-gray-200 animate-spin fill-blue-600" viewBox="0 0 100 101"
|
||||
fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path
|
||||
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
|
||||
fill="currentColor" />
|
||||
<path
|
||||
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
|
||||
fill="currentFill" />
|
||||
</svg>
|
||||
<span class="sr-only">Redirecting...</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="mt-6 text-sm">After login, you will be granted a one-time code to login to any device. You may complete
|
||||
this login on your desktop or any mobile browser and then use the token for any desktop or the Home Assistant
|
||||
app.</p>
|
||||
</div>
|
||||
<script>
|
||||
// Hide the login button and show the loader when clicked
|
||||
document.getElementById('oidc-login-btn').addEventListener('click', function () {
|
||||
this.classList.add('hidden');
|
||||
document.getElementById('loader').classList.remove('hidden');
|
||||
window.location.href = '/auth/oidc/redirect';
|
||||
});
|
||||
|
||||
// Show the direct login button if we already have a token
|
||||
if (localStorage.getItem('hassTokens')) {
|
||||
document.getElementById('signed-in').classList.remove('hidden');
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
139
docs/configuration.md
Normal file
139
docs/configuration.md
Normal file
@@ -0,0 +1,139 @@
|
||||
# Configuration methods
|
||||
|
||||
Currently, the only available configuration method is YAML in your `configuration.yaml` file. In the future, we will also add limited UI configuration for the most common configurations (Authentik, Authelia and Pocket-ID). Advanced users will need to use the YAML configuration in any case.
|
||||
|
||||
# YAML Configuration
|
||||
For now, this integration is configured using YAML in your `configuration.yaml` file. By default, only two fields are required:
|
||||
|
||||
```yaml
|
||||
auth_oidc:
|
||||
client_id: ""
|
||||
discovery_url: ""
|
||||
```
|
||||
|
||||
The default settings assume that you configure Home Assistant as a **public client**, without a client secret. If so, you should only need to provide the `client_id` from your OIDC provider and it's discovery URL (ending in `.well-known/openid-configuration`).
|
||||
You don't have to configure other settings in most cases, as they have secure defaults set. If your provider requires manually configuring the callback URL, use `<your HA URL>/auth/oidc/callback`.
|
||||
|
||||
## Provider Configurations
|
||||
Here are some documentation links for specific providers that you may want to follow:
|
||||
|
||||
| <img src="https://goauthentik.io/img/icon_top_brand_colour.svg" width="100"> | <img src="https://www.authelia.com/images/branding/logo-cropped.png" width="100"> | <img src="https://github.com/user-attachments/assets/4ceb2708-9f29-4694-b797-be833efce17d" width="100"> |
|
||||
|:-----------------------------------------------------------------------------------------:|:-------------------------------------------------------------------------------------:|:---------------------------------------------------------------------------------------:|
|
||||
| [Authentik](./provider-configurations/authentik.md) | [Authelia](./provider-configurations/authelia.md) | [Pocket ID](./provider-configurations/pocket-id.md) |
|
||||
|
||||
|
||||
Are you using another provider? Another user might have added configuration instructions here: [Other providers](./provider-configurations/other.md)
|
||||
|
||||
## Common Configurations
|
||||
### Configuring Client Secret
|
||||
If you want to configure Home Assistant as a **confidential client**, you should provide the client secret as well. An example configuration might look like this:
|
||||
|
||||
```yaml
|
||||
auth_oidc:
|
||||
client_id: ""
|
||||
client_secret: !secret oidc_client_secret
|
||||
discovery_url: ""
|
||||
```
|
||||
|
||||
You should use the Home Assistant secrets helper (`!secret`) to make sure you store secrets securely. See https://www.home-assistant.io/docs/configuration/secrets/ for more information.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Most users will not experience any benefits from using a confidential client, as using properly configured redirect URLs + PKCE already provides enough security in a home setting and using a client secret introduces the risk of it getting lost/stolen/put on the internet. Do not use a confidential setup if you don't know what you are doing.
|
||||
|
||||
### Configuring roles & scopes or OIDC settings
|
||||
|
||||
If your provider isn't listed above, you might want to configure OIDC settings yourself. Here's an example configuration for that use case:
|
||||
|
||||
```yaml
|
||||
auth_oidc:
|
||||
client_id: ""
|
||||
discovery_url: ""
|
||||
id_token_signing_alg: <HS256 or RS256>
|
||||
groups_scope: <groups scope>
|
||||
claims:
|
||||
display_name: <display name claim from your provider>
|
||||
username: <username claim from your provider>
|
||||
groups: <groups claim from your provider>
|
||||
roles:
|
||||
admin: <group name to use for admins>
|
||||
user: <group name to use for users>
|
||||
```
|
||||
|
||||
If you configure the user role, OIDC users that have neither configured group name will be rejected! If you configure the admin role, users with that role will receive administrator rights in Home Assistant automatically upon login.
|
||||
|
||||
### Configuring a display name for your OIDC provider
|
||||
If you would like to change the default name on the OIDC welcome screen and Home Assistant login screens from `OpenID Connect (SSO)` to your own display name, you can set the `display_name` configuration property.
|
||||
|
||||
```yaml
|
||||
auth_oidc:
|
||||
client_id: ""
|
||||
discovery_url: ""
|
||||
display_name: "Example"
|
||||
```
|
||||
|
||||
This will show the provider on the login screen as: "Login with Example".
|
||||
|
||||
### Migrating from HA username/password users to OIDC users
|
||||
If you already have users created within Home Assistant and would like to re-use the current user profile for your OIDC login, you can (temporarily) enable `features.automatic_user_linking`, with the following config (example):
|
||||
|
||||
```yaml
|
||||
auth_oidc:
|
||||
client_id: "someValueForTheClientId"
|
||||
discovery_url: "https://example.com/application/o/application/.well-known/openid-configuration"
|
||||
features:
|
||||
automatic_user_linking: true
|
||||
```
|
||||
|
||||
Upon login, OIDC users will then automatically be linked to the HA user with the same username. It's recommended to **only enable this temporarily** as it may pose a security risk. You should disable it after linking all your users, as existing links will still work if you disable it, but no new links will be created.
|
||||
|
||||
> [!CAUTION]
|
||||
> Any OIDC user with a username corresponding to a user in Home Assistant can get access to that user and all its rights/configuration.
|
||||
|
||||
> [!CAUTION]
|
||||
> MFA is ignored when using this setting, thus bypassing any MFA configuration the user has originally configured, as long as the username is an exact match. This is dangerous if you are not aware of it!
|
||||
|
||||
### Using a private certificate authority
|
||||
If you use a private certificate authority to secure your OIDC provider, you must configure the root certificates of your private certificate authority. Otherwise you will get an error (`[SSL: CERTIFICATE_VERIFY_FAILED]`) when connecting to the OIDC provider.
|
||||
|
||||
You can either make the CA known to the entire operating system or configure only this component to use the CA. If you want to only use your private CA with this integration, you can specify it via `network.tls_ca_path`:
|
||||
|
||||
```yaml
|
||||
auth_oidc:
|
||||
network:
|
||||
tls_ca_path: /path/to/private-ca.pem
|
||||
```
|
||||
|
||||
If you want to deactivate the validation of all TLS certificates for test purposes, you can do this via `network.tls_verify: false`:
|
||||
|
||||
```yaml
|
||||
auth_oidc:
|
||||
network:
|
||||
tls_verify: false
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> Do not disable `tls_verify` in a production setting or when your Home Assistant installation is exposed outside of your network. If disabled, man-in-the-middle attacks can be used to change the provider configuration to allow fake tokens to be used.
|
||||
|
||||
## All configuration Options
|
||||
|
||||
Here's a table of all options that you can set:
|
||||
|
||||
| Option | Type | Required | Default | Description |
|
||||
|-----------------------------|----------|----------|----------------------|---------------------------------------------------------------------------------------------------------|
|
||||
| `client_id` | `string` | Yes | | The Client ID as registered with your OpenID Connect provider. |
|
||||
| `client_secret` | `string` | No | | The Client Secret for enabling confidential client mode. |
|
||||
| `discovery_url` | `string` | Yes | | The OIDC well-known configuration URL. |
|
||||
| `display_name` | `string` | No | `"OpenID Connect (SSO)"` | The name to display on the login screen, both for the Home Assistant screen and the OIDC welcome screen. |
|
||||
| `id_token_signing_alg` | `string` | No | `RS256` | The signing algorithm that is used for your id_tokens.
|
||||
| `groups_scope` | `string` | No | `groups` | Override the default grups scope with another scope of your choice. |
|
||||
| `features.automatic_user_linking` | `boolean`| No | `false` | Automatically links users to existing Home Assistant users based on the OIDC username claim. Disabled by default for security. When disabled, OIDC users will get their own new user profile upon first login. |
|
||||
| `features.automatic_person_creation` | `boolean` | No | `true` | Automatically creates a person entry for new user profiles created by this integration. Recommended if you would like to assign presence detection to OIDC users. |
|
||||
| `features.disable_rfc7636` | `boolean`| No | `false` | Disables PKCE (RFC 7636) for OIDC providers that don't support it. You should not need this with most providers. |
|
||||
| `features.include_groups_scope` | `boolean` | No | `true` | Include the 'groups' scope in the OIDC request. Set to `false` to exclude it. |
|
||||
| `claims.display_name` | `string` | No | `name` | The claim to use to obtain the display name.
|
||||
| `claims.username` | `string` | No | `preferred_username` | The claim to use to obtain the username.
|
||||
| `claims.groups` | `string` | No | `groups` | The claim to use to obtain the user's group(s). |
|
||||
| `roles.admin` | `string` | No | `admins` | Group name to require for users to get the 'admin' role in Home Assistant. Defaults to 'admins', the default group name for admins in Authentik. Doesn't do anything if no groups claim is found in your token. |
|
||||
| `roles.user` | `string` | No | | Group name to require for users to get the 'user' role in Home Assistant. Defaults to giving all users this role, unless configured. |
|
||||
| `network.tls_verify` | `boolean` | No | `true` | Verify TLS certificate. You may want to set this set to `false` when testing locally. |
|
||||
| `network.tls_ca_path` | `string` | No | | Path to file containing a private certificate authority chain. |
|
||||
69
docs/provider-configurations/authelia.md
Normal file
69
docs/provider-configurations/authelia.md
Normal file
@@ -0,0 +1,69 @@
|
||||
# Authelia
|
||||
|
||||
## Public client configuration
|
||||
|
||||
> [!NOTE]
|
||||
> This configuration strictly requires a HTTPS redirect uri.
|
||||
|
||||
Authelia `configuration.yml`
|
||||
```yaml
|
||||
identity_providers:
|
||||
oidc:
|
||||
## The other portions of the mandatory OpenID Connect 1.0 configuration go here.
|
||||
## See: https://www.authelia.com/c/oidc
|
||||
clients:
|
||||
- client_id: 'homeassistant'
|
||||
client_name: 'Home Assistant'
|
||||
public: true
|
||||
require_pkce: true
|
||||
pkce_challenge_method: 'S256'
|
||||
authorization_policy: 'two_factor'
|
||||
redirect_uris:
|
||||
- 'https://hass.example.com/auth/oidc/callback'
|
||||
scopes:
|
||||
- 'openid'
|
||||
- 'profile'
|
||||
- 'groups'
|
||||
userinfo_signed_response_alg: 'RS256'
|
||||
```
|
||||
|
||||
Home Assistant `configuration.yaml`
|
||||
```yaml
|
||||
auth_oidc:
|
||||
client_id: "homeassistant"
|
||||
discovery_url: "https://auth.example.com/.well-known/openid-configuration"
|
||||
```
|
||||
|
||||
## Confidential client configuration:
|
||||
|
||||
Authelia `configuration.yml`
|
||||
```yaml
|
||||
identity_providers:
|
||||
oidc:
|
||||
## The other portions of the mandatory OpenID Connect 1.0 configuration go here.
|
||||
## See: https://www.authelia.com/c/oidc
|
||||
clients:
|
||||
- client_id: 'homeassistant'
|
||||
client_name: 'Home Assistant'
|
||||
client_secret: '$pbkdf2-sha512$310000$c8p78n7pUMln0jzvd4aK4Q$JNRBzwAo0ek5qKn50cFzzvE9RXV88h1wJn5KGiHrD0YKtZaR/nCb2CJPOsKaPK0hjf.9yHxzQGZziziccp6Yng' # The digest of 'insecure_secret'.
|
||||
public: false
|
||||
require_pkce: true
|
||||
pkce_challenge_method: 'S256'
|
||||
authorization_policy: 'two_factor'
|
||||
redirect_uris:
|
||||
- 'https://hass.example.com/auth/oidc/callback'
|
||||
scopes:
|
||||
- 'openid'
|
||||
- 'profile'
|
||||
- 'groups'
|
||||
userinfo_signed_response_alg: 'RS256'
|
||||
token_endpoint_auth_method: 'client_secret_post'
|
||||
```
|
||||
|
||||
Home Assistant `configuration.yaml`
|
||||
```yaml
|
||||
auth_oidc:
|
||||
client_id: "homeassistant"
|
||||
client_secret: "insecure_secret"
|
||||
discovery_url: "https://auth.example.com/.well-known/openid-configuration"
|
||||
```
|
||||
40
docs/provider-configurations/authentik.md
Normal file
40
docs/provider-configurations/authentik.md
Normal file
@@ -0,0 +1,40 @@
|
||||
# Authentik
|
||||
|
||||
## Public client configuration
|
||||
Under construction.
|
||||
|
||||
## Confidential client configuration
|
||||
|
||||
1. From the admin interface, go to `Applications > Providers` and click on `Create`
|
||||
2. Select `OAuth2/OpenID Provider` and click `Next`
|
||||
3. Fill the following details:
|
||||
- Name: `Home Assistant Provider`
|
||||
- Authorization flow: `default-provider-authorization-explicit-consent`
|
||||
- Client type: `Confidential`
|
||||
- Client ID: `homeassistant`
|
||||
- Client Secret: **Copy this value**
|
||||
- Redirect URIs/Origins: Click on `Add entry` (You can use either DNS, Internal/External IP or localhost)
|
||||
- Strict: https://hass.example.com/auth/oidc/callback
|
||||
4. Click `Finish` to save the provider configuration
|
||||
5. Open the created Provider
|
||||
6. On the Assigned to application section click on `Create`:
|
||||
- Name: `Home Assistant`
|
||||
- Slug: `home-assistant`
|
||||
- Provider: `Home Assistant Provider`
|
||||
|
||||
Then save the configuration
|
||||
|
||||
## Home Assistant configuration
|
||||
|
||||
> [!IMPORTANT]
|
||||
> For HTTPS configuration make sure to have a public valid SSL certificate (i.e. LetsEncrypt), if not, use HTTP instead (more insecure) or add your Authentik CA certificate to `network.tls_ca_path`.
|
||||
|
||||
After installing this HACS addon, edit your `configuration.yaml` file and add:
|
||||
```yaml
|
||||
auth_oidc:
|
||||
client_id: "homeassistant"
|
||||
client_secret: "client_secret"
|
||||
discovery_url: "https://auth.example.com/application/o/home-assistant/.well-known/openid-configuration"
|
||||
```
|
||||
|
||||
Restart Home Assistant and go to https://hass.example.com/auth/oidc/welcome
|
||||
2
docs/provider-configurations/other.md
Normal file
2
docs/provider-configurations/other.md
Normal file
@@ -0,0 +1,2 @@
|
||||
# Other providers
|
||||
Under construction.
|
||||
2
docs/provider-configurations/pocket-id.md
Normal file
2
docs/provider-configurations/pocket-id.md
Normal file
@@ -0,0 +1,2 @@
|
||||
# Pocket ID
|
||||
Under construction.
|
||||
84
docs/usage.md
Normal file
84
docs/usage.md
Normal file
@@ -0,0 +1,84 @@
|
||||
# How do I use the OIDC Integration for Home Assistant?
|
||||
|
||||
Here's a step by step guide to use the integration:
|
||||
|
||||
### Step 1: HACS
|
||||
Install the integration through [HACS](https://hacs.xyz/). You can add it automatically using the button below, or use the Github URL and type `Integration` in the manual Custom Repository add dialog.
|
||||
|
||||
[](https://my.home-assistant.io/redirect/hacs_repository/?owner=christiaangoossens&repository=hass-oidc-auth&category=Integration)
|
||||
|
||||
|
||||
### Step 2: Configuration of the integration
|
||||
The integration is currently configurable through YAML only. See the [Configuration Guide](./docs/configuration.md) for more details or pick your OIDC provider below:
|
||||
|
||||
| <img src="https://goauthentik.io/img/icon_top_brand_colour.svg" width="100"> | <img src="https://www.authelia.com/images/branding/logo-cropped.png" width="100"> | <img src="https://github.com/user-attachments/assets/4ceb2708-9f29-4694-b797-be833efce17d" width="100"> |
|
||||
|:-----------------------------------------------------------------------------------------:|:-------------------------------------------------------------------------------------:|:---------------------------------------------------------------------------------------:|
|
||||
| [Authentik](./provider-configurations/authentik.md) | [Authelia](./provider-configurations/authelia.md) | [Pocket ID](./provider-configurations/pocket-id.md) |
|
||||
|
||||
By default, the integration assumes you configure Home Assistant as a **public client** and thus only specify the `client_id` and no `client_secret`. For example, your configuration might look like:
|
||||
|
||||
```yaml
|
||||
auth_oidc:
|
||||
client_id: "example"
|
||||
discovery_url: "https://example.com/.well-known/openid-configuration"
|
||||
```
|
||||
|
||||
When registering Home Assistant at your OIDC provider, use `<your HA URL>/auth/oidc/callback` as the callback URL and select 'public client'. You should now get the `client_id` and `issuer_url` or `discovery_url` to fill in.
|
||||
|
||||
### Step 3: Restart
|
||||
Restart Home Assistant. You can do so by going to the Reparations/Update section in Home Assistant.
|
||||
|
||||
### Step 4: Go to the OIDC login screen
|
||||
After restarting Home Assistant, you should now be able to get to the login screen. You can find it at `<your HA URL>/auth/oidc/welcome`. You will have to go there manually for now. For example, it might be located at http://homeassistant.local:8123/auth/oidc/welcome.
|
||||
|
||||
It should look like this:
|
||||
|
||||

|
||||
|
||||
If you have configured everything correctly, you should be redirected to your OIDC Provider after clicking the button. Please login there.
|
||||
|
||||
You should return to a screen like this:
|
||||
|
||||

|
||||
|
||||
Either click the automatic sign in button or copy the code.
|
||||
This screen will give you a one-time code to login that expires in 5 minutes.
|
||||
|
||||
#### Step 4a: Automatic login
|
||||
If you would like to login automatically, click the button. It will log you in to your user in the current browser window.
|
||||
|
||||
#### Step 4b: Code login
|
||||
If you would like to login using the code, go to your normal Home Assistant URL without any user logged in, such as on your mobile device/wall tablet/smart watch. You will now see the following screen:
|
||||
|
||||

|
||||
|
||||
If you don't, you likely see:
|
||||
|
||||

|
||||
|
||||
If so, click "OpenID Connect (SSO)" to get to the first screen. If you have configured a [display name](./configuration.md#configuring-a-display-name-for-your-oidc-provider), that will show instead.
|
||||
|
||||
Enter your code into the single input field:
|
||||
|
||||

|
||||
|
||||
Upon clicking login, you should now login.
|
||||
If the code is wrong, you will see this instead:
|
||||
|
||||

|
||||
|
||||
#### Step 5: Logged in
|
||||
You will be logged in after following this guide.
|
||||
|
||||
With the default configuration, [a person entry](https://www.home-assistant.io/integrations/person/) will be created for every new OIDC user logging in. New OIDC users will get their own fresh user, linked to their persistent ID (subject) at the OpenID Connect provider. You may change your name, username or email at the provider and still have the same Home Assistant user profile.
|
||||
|
||||
# How can I make this easier for my users?
|
||||
|
||||
You can link the user directly to one of these following URLs:
|
||||
|
||||
- `/auth/oidc/welcome` (if you would like a nice welcome screen for your users)
|
||||
- `/auth/oidc/redirect` (if you would like to just redirect them without a welcome screen)
|
||||
|
||||
For a seamless user experience, configure a new domain on your proxy to redirect to the `/auth/oidc/welcome` path or configure that path on your homelab dashboard or in your OIDC provider (such as in the app settings in Authentik). Users will then always start on the OIDC welcome page, which will allow them to visit the dashboard if they are already logged in.
|
||||
|
||||
*Note: do not replace the standard path with a redirect to the OIDC screen. This breaks login with code.*
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"name": "OpenID Connect",
|
||||
"hide_default_branch": true,
|
||||
"render_readme": true,
|
||||
"homeassistant": "2024.12"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "hass-oidc"
|
||||
version = "0.1.0"
|
||||
name = "hass-oidc-auth"
|
||||
version = "0.5.1"
|
||||
description = "OIDC component for Home Assistant"
|
||||
authors = [
|
||||
{ name = "Christiaan Goossens", email = "contact@christiaangoossens.nl" }
|
||||
@@ -8,9 +8,12 @@ authors = [
|
||||
license = "MIT"
|
||||
dependencies = [
|
||||
"python-jose>=3.3.0",
|
||||
"aiofiles>=24.1.0",
|
||||
"jinja2>=3.1.4",
|
||||
"bcrypt>=4.2.0",
|
||||
]
|
||||
readme = "README.md"
|
||||
requires-python = ">= 3.8"
|
||||
requires-python = ">= 3.13"
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
@@ -28,3 +31,12 @@ allow-direct-references = true
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["custom_components/auth_oidc"]
|
||||
|
||||
[tool.rye.scripts]
|
||||
check = { chain = ["check-lint", "check-fmt", "check-pylint" ] }
|
||||
"check-lint" = "rye lint"
|
||||
"check-fmt" = "rye fmt --check"
|
||||
"check-pylint" = "pylint custom_components"
|
||||
fix = { chain = ["fix-lint", "fix-fmt" ] }
|
||||
"fix-lint" = "rye lint --fix"
|
||||
"fix-fmt" = "rye fmt"
|
||||
|
||||
44
renovate.json
Normal file
44
renovate.json
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"config:recommended"
|
||||
],
|
||||
"schedule": [
|
||||
"every weekend"
|
||||
],
|
||||
"vulnerabilityAlerts": {
|
||||
"groupName": "vulnerabilityAlerts",
|
||||
"enabled": true,
|
||||
"schedule": [
|
||||
"after 6am and before 6pm"
|
||||
],
|
||||
"prCreation": "immediate"
|
||||
},
|
||||
"packageRules": [
|
||||
{
|
||||
"description": "Group all GitHub Actions updates",
|
||||
"matchDatasources": [
|
||||
"github-actions"
|
||||
],
|
||||
"groupName": "Github Actions Updates",
|
||||
"automerge": true
|
||||
},
|
||||
{
|
||||
"description": "Version updates for Home Assistant packages",
|
||||
"groupName": "Home Assistant Update",
|
||||
"matchPackageNames": [
|
||||
"homeassistant",
|
||||
"jinja2",
|
||||
"bcrypt"
|
||||
],
|
||||
"automerge": false
|
||||
},
|
||||
{
|
||||
"description": "Version updates for other pip packages",
|
||||
"matchDatasources": [
|
||||
"pypi"
|
||||
],
|
||||
"automerge": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -14,6 +14,8 @@ acme==3.0.1
|
||||
# via hass-nabucasa
|
||||
aiodns==3.2.0
|
||||
# via homeassistant
|
||||
aiofiles==24.1.0
|
||||
# via hass-oidc-auth
|
||||
aiohappyeyeballs==2.4.4
|
||||
# via aiohttp
|
||||
aiohasupervisor==0.2.1
|
||||
@@ -60,6 +62,7 @@ audioop-lts==0.2.1
|
||||
awesomeversion==24.6.0
|
||||
# via homeassistant
|
||||
bcrypt==4.2.0
|
||||
# via hass-oidc-auth
|
||||
# via homeassistant
|
||||
bleak==0.22.3
|
||||
# via bleak-retry-connector
|
||||
@@ -145,6 +148,7 @@ ifaddr==0.2.0
|
||||
isort==5.13.2
|
||||
# via pylint
|
||||
jinja2==3.1.4
|
||||
# via hass-oidc-auth
|
||||
# via homeassistant
|
||||
jmespath==1.0.1
|
||||
# via boto3
|
||||
@@ -206,7 +210,7 @@ pyric==0.1.6.3
|
||||
python-dateutil==2.9.0.post0
|
||||
# via botocore
|
||||
python-jose==3.3.0
|
||||
# via hass-oidc
|
||||
# via hass-oidc-auth
|
||||
python-slugify==8.0.4
|
||||
# via homeassistant
|
||||
pytz==2024.2
|
||||
|
||||
@@ -10,13 +10,21 @@
|
||||
# universal: false
|
||||
|
||||
-e file:.
|
||||
aiofiles==24.1.0
|
||||
# via hass-oidc-auth
|
||||
bcrypt==4.2.1
|
||||
# via hass-oidc-auth
|
||||
ecdsa==0.19.0
|
||||
# via python-jose
|
||||
jinja2==3.1.5
|
||||
# via hass-oidc-auth
|
||||
markupsafe==3.0.2
|
||||
# via jinja2
|
||||
pyasn1==0.6.1
|
||||
# via python-jose
|
||||
# via rsa
|
||||
python-jose==3.3.0
|
||||
# via hass-oidc
|
||||
# via hass-oidc-auth
|
||||
rsa==4.9
|
||||
# via python-jose
|
||||
six==1.17.0
|
||||
|
||||
Reference in New Issue
Block a user