prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  404 error for kubernetes depoyment
  **Describe the bug**
  /if/flow/initial-setup/ endpoint in the browser gives a 404 not found error
  
  **To Reproduce**
  Steps to reproduce the behavior:
  1. Go to 'https://goauthentik.io/docs/installation/kubernetes'
  2. Create Values.yaml
  3. run helm commands
  4. all pods are up and running
  5. go to browser http://<ing-url>/if/flow/initial-setup/
  
  **Expected behavior**
  Page should load letting me setup ak-admin password
  
  **Screenshots**
  404 not found
  
  **Logs**
  {"event": "/api/v3/outposts/instances/", "host": "localhost:8000", "level": "info", "logger": "authentik.asgi", "method": "GET", "pid": 24, "remote": "127.0.0.1", "request_id": "454efe5b57f34713bf837681449b91a6", "runtime": 35, "scheme": "http", "status": 403, "timestamp": "2022-07-11T10:39:00.436171", "user": "", "user_agent": "goauthentik.io/outpost/2022.7.2"}
  {"event": "Forbidden: /api/v3/outposts/instances/", "level": "warning", "logger": "django.request", "timestamp": 1657535940.437195}
  {"error":"403 Forbidden","event":"Failed to fetch outpost configuration, retrying in 3 seconds","level":"error","logger":"authentik.outpost.ak-api-controller","timestamp":"2022-07-11T10:39:00Z"}
  **Version and Deployment (please complete the following information):**
   - authentik version: authentik-2022.7.2 
   - Deployment: [kubectl 1.21, helm v3.1.0]
  
  **Additional context**
  Add any other context about the problem here.
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `lifecycle/migrate.py`
  Content:
  ```
  1 #!/usr/bin/env python
  2 """System Migration handler"""
  3 import os
  4 from importlib.util import module_from_spec, spec_from_file_location
  5 from inspect import getmembers, isclass
  6 from pathlib import Path
  7 from typing import Any
  8 
  9 from psycopg2 import connect
  10 from structlog.stdlib import get_logger
  11 
  12 from authentik.lib.config import CONFIG
  13 
  14 LOGGER = get_logger()
  15 ADV_LOCK_UID = 1000
  16 LOCKED = False
  17 
  18 
  19 class BaseMigration:
  20     """Base System Migration"""
  21 
  22     cur: Any
  23     con: Any
  24 
  25     def __init__(self, cur: Any, con: Any):
  26         self.cur = cur
  27         self.con = con
  28 
  29     def needs_migration(self) -> bool:
  30         """Return true if Migration needs to be run"""
  31         return False
  32 
  33     def run(self):
  34         """Run the actual migration"""
  35 
  36 
  37 def wait_for_lock():
  38     """lock an advisory lock to prevent multiple instances from migrating at once"""
  39     LOGGER.info("waiting to acquire database lock")
  40     curr.execute("SELECT pg_advisory_lock(%s)", (ADV_LOCK_UID,))
  41     # pylint: disable=global-statement
  42     global LOCKED
  43     LOCKED = True
  44 
  45 
  46 def release_lock():
  47     """Release database lock"""
  48     if not LOCKED:
  49         return
  50     curr.execute("SELECT pg_advisory_unlock(%s)", (ADV_LOCK_UID,))
  51 
  52 
  53 if __name__ == "__main__":
  54 
  55     conn = connect(
  56         dbname=CONFIG.y("postgresql.name"),
  57         user=CONFIG.y("postgresql.user"),
  58         password=CONFIG.y("postgresql.password"),
  59         host=CONFIG.y("postgresql.host"),
  60         port=int(CONFIG.y("postgresql.port")),
  61     )
  62     curr = conn.cursor()
  63     try:
  64         for migration in Path(__file__).parent.absolute().glob("system_migrations/*.py"):
  65             spec = spec_from_file_location("lifecycle.system_migrations", migration)
  66             mod = module_from_spec(spec)
  67             # pyright: reportGeneralTypeIssues=false
  68             spec.loader.exec_module(mod)
  69 
  70             for name, sub in getmembers(mod, isclass):
  71                 if name != "Migration":
  72                     continue
  73                 migration = sub(curr, conn)
  74                 if migration.needs_migration():
  75                     wait_for_lock()
  76                     LOGGER.info("Migration needs to be applied", migration=sub)
  77                     migration.run()
  78                     LOGGER.info("Migration finished applying", migration=sub)
  79                     release_lock()
  80         LOGGER.info("applying django migrations")
  81         os.environ.setdefault("DJANGO_SETTINGS_MODULE", "authentik.root.settings")
  82         wait_for_lock()
  83         try:
  84             from django.core.management import execute_from_command_line
  85         except ImportError as exc:
  86             raise ImportError(
  87                 "Couldn't import Django. Are you sure it's installed and "
  88                 "available on your PYTHONPATH environment variable? Did you "
  89                 "forget to activate a virtual environment?"
  90             ) from exc
  91         execute_from_command_line(["", "migrate"])
  92     finally:
  93         release_lock()
  94
  ```
  
  Path: `authentik/managed/tasks.py`
  Content:
  ```
  1 """managed tasks"""
  2 from django.db import DatabaseError
  3 
  4 from authentik.core.tasks import CELERY_APP
  5 from authentik.events.monitored_tasks import (
  6     MonitoredTask,
  7     TaskResult,
  8     TaskResultStatus,
  9     prefill_task,
  10 )
  11 from authentik.managed.manager import ObjectManager
  12 
  13 
  14 @CELERY_APP.task(bind=True, base=MonitoredTask)
  15 @prefill_task
  16 def managed_reconcile(self: MonitoredTask):
  17     """Run ObjectManager to ensure objects are up-to-date"""
  18     try:
  19         ObjectManager().run()
  20         self.set_status(
  21             TaskResult(TaskResultStatus.SUCCESSFUL, ["Successfully updated managed models."])
  22         )
  23     except DatabaseError as exc:  # pragma: no cover
  24         self.set_status(TaskResult(TaskResultStatus.WARNING, [str(exc)]))
  25
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/authentik/managed/tasks.py b/authentik/managed/tasks.py
  --- a/authentik/managed/tasks.py
  +++ b/authentik/managed/tasks.py
  @@ -11,7 +11,11 @@
   from authentik.managed.manager import ObjectManager
   
   
  -@CELERY_APP.task(bind=True, base=MonitoredTask)
  +@CELERY_APP.task(
  +    bind=True,
  +    base=MonitoredTask,
  +    retry_backoff=True,
  +)
   @prefill_task
   def managed_reconcile(self: MonitoredTask):
       """Run ObjectManager to ensure objects are up-to-date"""
  @@ -22,3 +26,4 @@
           )
       except DatabaseError as exc:  # pragma: no cover
           self.set_status(TaskResult(TaskResultStatus.WARNING, [str(exc)]))
  +        self.retry()
  diff --git a/lifecycle/migrate.py b/lifecycle/migrate.py
  --- a/lifecycle/migrate.py
  +++ b/lifecycle/migrate.py
  @@ -1,6 +1,7 @@
   #!/usr/bin/env python
   """System Migration handler"""
   import os
  +import sys
   from importlib.util import module_from_spec, spec_from_file_location
   from inspect import getmembers, isclass
   from pathlib import Path
  @@ -50,7 +51,16 @@
       curr.execute("SELECT pg_advisory_unlock(%s)", (ADV_LOCK_UID,))
   
   
  +def is_locked():
  +    """Check if lock is currently active (used by worker to wait for migrations)"""
  +    curr.executor("SELECT count(*) FROM pg_locks WHERE objid = %s", (ADV_LOCK_UID,))
  +    return curr.rowcount
  +
  +
   if __name__ == "__main__":
  +    if len(sys.argv) > 1:
  +        if sys.argv[1] == "check_lock":
  +            sys.exit(is_locked())
   
       conn = connect(
           dbname=CONFIG.y("postgresql.name"),
  
verification_info: {"golden_diff": "diff --git a/authentik/managed/tasks.py b/authentik/managed/tasks.py\n--- a/authentik/managed/tasks.py\n+++ b/authentik/managed/tasks.py\n@@ -11,7 +11,11 @@\n from authentik.managed.manager import ObjectManager\n \n \n-@CELERY_APP.task(bind=True, base=MonitoredTask)\n+@CELERY_APP.task(\n+    bind=True,\n+    base=MonitoredTask,\n+    retry_backoff=True,\n+)\n @prefill_task\n def managed_reconcile(self: MonitoredTask):\n     \"\"\"Run ObjectManager to ensure objects are up-to-date\"\"\"\n@@ -22,3 +26,4 @@\n         )\n     except DatabaseError as exc:  # pragma: no cover\n         self.set_status(TaskResult(TaskResultStatus.WARNING, [str(exc)]))\n+        self.retry()\ndiff --git a/lifecycle/migrate.py b/lifecycle/migrate.py\n--- a/lifecycle/migrate.py\n+++ b/lifecycle/migrate.py\n@@ -1,6 +1,7 @@\n #!/usr/bin/env python\n \"\"\"System Migration handler\"\"\"\n import os\n+import sys\n from importlib.util import module_from_spec, spec_from_file_location\n from inspect import getmembers, isclass\n from pathlib import Path\n@@ -50,7 +51,16 @@\n     curr.execute(\"SELECT pg_advisory_unlock(%s)\", (ADV_LOCK_UID,))\n \n \n+def is_locked():\n+    \"\"\"Check if lock is currently active (used by worker to wait for migrations)\"\"\"\n+    curr.executor(\"SELECT count(*) FROM pg_locks WHERE objid = %s\", (ADV_LOCK_UID,))\n+    return curr.rowcount\n+\n+\n if __name__ == \"__main__\":\n+    if len(sys.argv) > 1:\n+        if sys.argv[1] == \"check_lock\":\n+            sys.exit(is_locked())\n \n     conn = connect(\n         dbname=CONFIG.y(\"postgresql.name\"),\n", "issue": "404 error for kubernetes depoyment\n**Describe the bug**\r\n/if/flow/initial-setup/ endpoint in the browser gives a 404 not found error\r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n1. Go to 'https://goauthentik.io/docs/installation/kubernetes'\r\n2. Create Values.yaml\r\n3. run helm commands\r\n4. all pods are up and running\r\n5. go to browser http://<ing-url>/if/flow/initial-setup/\r\n\r\n**Expected behavior**\r\nPage should load letting me setup ak-admin password\r\n\r\n**Screenshots**\r\n404 not found\r\n\r\n**Logs**\r\n{\"event\": \"/api/v3/outposts/instances/\", \"host\": \"localhost:8000\", \"level\": \"info\", \"logger\": \"authentik.asgi\", \"method\": \"GET\", \"pid\": 24, \"remote\": \"127.0.0.1\", \"request_id\": \"454efe5b57f34713bf837681449b91a6\", \"runtime\": 35, \"scheme\": \"http\", \"status\": 403, \"timestamp\": \"2022-07-11T10:39:00.436171\", \"user\": \"\", \"user_agent\": \"goauthentik.io/outpost/2022.7.2\"}\r\n{\"event\": \"Forbidden: /api/v3/outposts/instances/\", \"level\": \"warning\", \"logger\": \"django.request\", \"timestamp\": 1657535940.437195}\r\n{\"error\":\"403 Forbidden\",\"event\":\"Failed to fetch outpost configuration, retrying in 3 seconds\",\"level\":\"error\",\"logger\":\"authentik.outpost.ak-api-controller\",\"timestamp\":\"2022-07-11T10:39:00Z\"}\r\n**Version and Deployment (please complete the following information):**\r\n - authentik version: authentik-2022.7.2 \r\n - Deployment: [kubectl 1.21, helm v3.1.0]\r\n\r\n**Additional context**\r\nAdd any other context about the problem here.\r\n\n", "before_files": [{"content": "#!/usr/bin/env python\n\"\"\"System Migration handler\"\"\"\nimport os\nfrom importlib.util import module_from_spec, spec_from_file_location\nfrom inspect import getmembers, isclass\nfrom pathlib import Path\nfrom typing import Any\n\nfrom psycopg2 import connect\nfrom structlog.stdlib import get_logger\n\nfrom authentik.lib.config import CONFIG\n\nLOGGER = get_logger()\nADV_LOCK_UID = 1000\nLOCKED = False\n\n\nclass BaseMigration:\n    \"\"\"Base System Migration\"\"\"\n\n    cur: Any\n    con: Any\n\n    def __init__(self, cur: Any, con: Any):\n        self.cur = cur\n        self.con = con\n\n    def needs_migration(self) -> bool:\n        \"\"\"Return true if Migration needs to be run\"\"\"\n        return False\n\n    def run(self):\n        \"\"\"Run the actual migration\"\"\"\n\n\ndef wait_for_lock():\n    \"\"\"lock an advisory lock to prevent multiple instances from migrating at once\"\"\"\n    LOGGER.info(\"waiting to acquire database lock\")\n    curr.execute(\"SELECT pg_advisory_lock(%s)\", (ADV_LOCK_UID,))\n    # pylint: disable=global-statement\n    global LOCKED\n    LOCKED = True\n\n\ndef release_lock():\n    \"\"\"Release database lock\"\"\"\n    if not LOCKED:\n        return\n    curr.execute(\"SELECT pg_advisory_unlock(%s)\", (ADV_LOCK_UID,))\n\n\nif __name__ == \"__main__\":\n\n    conn = connect(\n        dbname=CONFIG.y(\"postgresql.name\"),\n        user=CONFIG.y(\"postgresql.user\"),\n        password=CONFIG.y(\"postgresql.password\"),\n        host=CONFIG.y(\"postgresql.host\"),\n        port=int(CONFIG.y(\"postgresql.port\")),\n    )\n    curr = conn.cursor()\n    try:\n        for migration in Path(__file__).parent.absolute().glob(\"system_migrations/*.py\"):\n            spec = spec_from_file_location(\"lifecycle.system_migrations\", migration)\n            mod = module_from_spec(spec)\n            # pyright: reportGeneralTypeIssues=false\n            spec.loader.exec_module(mod)\n\n            for name, sub in getmembers(mod, isclass):\n                if name != \"Migration\":\n                    continue\n                migration = sub(curr, conn)\n                if migration.needs_migration():\n                    wait_for_lock()\n                    LOGGER.info(\"Migration needs to be applied\", migration=sub)\n                    migration.run()\n                    LOGGER.info(\"Migration finished applying\", migration=sub)\n                    release_lock()\n        LOGGER.info(\"applying django migrations\")\n        os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"authentik.root.settings\")\n        wait_for_lock()\n        try:\n            from django.core.management import execute_from_command_line\n        except ImportError as exc:\n            raise ImportError(\n                \"Couldn't import Django. Are you sure it's installed and \"\n                \"available on your PYTHONPATH environment variable? Did you \"\n                \"forget to activate a virtual environment?\"\n            ) from exc\n        execute_from_command_line([\"\", \"migrate\"])\n    finally:\n        release_lock()\n", "path": "lifecycle/migrate.py"}, {"content": "\"\"\"managed tasks\"\"\"\nfrom django.db import DatabaseError\n\nfrom authentik.core.tasks import CELERY_APP\nfrom authentik.events.monitored_tasks import (\n    MonitoredTask,\n    TaskResult,\n    TaskResultStatus,\n    prefill_task,\n)\nfrom authentik.managed.manager import ObjectManager\n\n\n@CELERY_APP.task(bind=True, base=MonitoredTask)\n@prefill_task\ndef managed_reconcile(self: MonitoredTask):\n    \"\"\"Run ObjectManager to ensure objects are up-to-date\"\"\"\n    try:\n        ObjectManager().run()\n        self.set_status(\n            TaskResult(TaskResultStatus.SUCCESSFUL, [\"Successfully updated managed models.\"])\n        )\n    except DatabaseError as exc:  # pragma: no cover\n        self.set_status(TaskResult(TaskResultStatus.WARNING, [str(exc)]))\n", "path": "authentik/managed/tasks.py"}], "after_files": [{"content": "#!/usr/bin/env python\n\"\"\"System Migration handler\"\"\"\nimport os\nimport sys\nfrom importlib.util import module_from_spec, spec_from_file_location\nfrom inspect import getmembers, isclass\nfrom pathlib import Path\nfrom typing import Any\n\nfrom psycopg2 import connect\nfrom structlog.stdlib import get_logger\n\nfrom authentik.lib.config import CONFIG\n\nLOGGER = get_logger()\nADV_LOCK_UID = 1000\nLOCKED = False\n\n\nclass BaseMigration:\n    \"\"\"Base System Migration\"\"\"\n\n    cur: Any\n    con: Any\n\n    def __init__(self, cur: Any, con: Any):\n        self.cur = cur\n        self.con = con\n\n    def needs_migration(self) -> bool:\n        \"\"\"Return true if Migration needs to be run\"\"\"\n        return False\n\n    def run(self):\n        \"\"\"Run the actual migration\"\"\"\n\n\ndef wait_for_lock():\n    \"\"\"lock an advisory lock to prevent multiple instances from migrating at once\"\"\"\n    LOGGER.info(\"waiting to acquire database lock\")\n    curr.execute(\"SELECT pg_advisory_lock(%s)\", (ADV_LOCK_UID,))\n    # pylint: disable=global-statement\n    global LOCKED\n    LOCKED = True\n\n\ndef release_lock():\n    \"\"\"Release database lock\"\"\"\n    if not LOCKED:\n        return\n    curr.execute(\"SELECT pg_advisory_unlock(%s)\", (ADV_LOCK_UID,))\n\n\ndef is_locked():\n    \"\"\"Check if lock is currently active (used by worker to wait for migrations)\"\"\"\n    curr.executor(\"SELECT count(*) FROM pg_locks WHERE objid = %s\", (ADV_LOCK_UID,))\n    return curr.rowcount\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) > 1:\n        if sys.argv[1] == \"check_lock\":\n            sys.exit(is_locked())\n\n    conn = connect(\n        dbname=CONFIG.y(\"postgresql.name\"),\n        user=CONFIG.y(\"postgresql.user\"),\n        password=CONFIG.y(\"postgresql.password\"),\n        host=CONFIG.y(\"postgresql.host\"),\n        port=int(CONFIG.y(\"postgresql.port\")),\n    )\n    curr = conn.cursor()\n    try:\n        for migration in Path(__file__).parent.absolute().glob(\"system_migrations/*.py\"):\n            spec = spec_from_file_location(\"lifecycle.system_migrations\", migration)\n            mod = module_from_spec(spec)\n            # pyright: reportGeneralTypeIssues=false\n            spec.loader.exec_module(mod)\n\n            for name, sub in getmembers(mod, isclass):\n                if name != \"Migration\":\n                    continue\n                migration = sub(curr, conn)\n                if migration.needs_migration():\n                    wait_for_lock()\n                    LOGGER.info(\"Migration needs to be applied\", migration=sub)\n                    migration.run()\n                    LOGGER.info(\"Migration finished applying\", migration=sub)\n                    release_lock()\n        LOGGER.info(\"applying django migrations\")\n        os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"authentik.root.settings\")\n        wait_for_lock()\n        try:\n            from django.core.management import execute_from_command_line\n        except ImportError as exc:\n            raise ImportError(\n                \"Couldn't import Django. Are you sure it's installed and \"\n                \"available on your PYTHONPATH environment variable? Did you \"\n                \"forget to activate a virtual environment?\"\n            ) from exc\n        execute_from_command_line([\"\", \"migrate\"])\n    finally:\n        release_lock()\n", "path": "lifecycle/migrate.py"}, {"content": "\"\"\"managed tasks\"\"\"\nfrom django.db import DatabaseError\n\nfrom authentik.core.tasks import CELERY_APP\nfrom authentik.events.monitored_tasks import (\n    MonitoredTask,\n    TaskResult,\n    TaskResultStatus,\n    prefill_task,\n)\nfrom authentik.managed.manager import ObjectManager\n\n\n@CELERY_APP.task(\n    bind=True,\n    base=MonitoredTask,\n    retry_backoff=True,\n)\n@prefill_task\ndef managed_reconcile(self: MonitoredTask):\n    \"\"\"Run ObjectManager to ensure objects are up-to-date\"\"\"\n    try:\n        ObjectManager().run()\n        self.set_status(\n            TaskResult(TaskResultStatus.SUCCESSFUL, [\"Successfully updated managed models.\"])\n        )\n    except DatabaseError as exc:  # pragma: no cover\n        self.set_status(TaskResult(TaskResultStatus.WARNING, [str(exc)]))\n        self.retry()\n", "path": "authentik/managed/tasks.py"}]}