on master help sign in
Merge pull request #300 from obsidiansystems/is-apk-signing-revision

Manage Android signing keys correctly for app release versions

commit679c66c07090c2a26b4ed0014138dc8a4fa0bb26 authorLuigy Leon <luichi.19@gmail.com> dateTue 20 Nov 2018, 10:17 (8 years ago) parentbe079feb2437c9
6 files changed+130−39
README.md+9−27 default.nix+6 lib/command/obelisk-command.cabal+2 lib/command/src/Obelisk/Command.hs+4−8 lib/command/src/Obelisk/Command/Deploy.hs+108−4 lib/command/src/Obelisk/Command/Nix.hs+1
README.md+9−27
@@ -247,38 +247,20 @@ Now deploy the built apk file to your Android device:
2472471. Connect the device using USB (be sure to confirm any security prompts on the device)
2482481. Run the deploy script: `result-android/bin/deploy`
249249
250−This should copy over and install the application on your device (if you see a "*signatures do not match*" error, simply uninstall the previous app from the device before retrying the deploy). The name of the installed application will be what you have specified for `android.displayName` in the `default.nix`.
251−
252−#### Releasing to Play Store
250+Alternatively, you can deploy from an obelisk deployment directory (a directory generated post `ob deploy init ...` command) using the `ob deploy test android` command.
251+This command will accomplish the following:
253252
254−##### Configure signing
253+1. Create a key store and apk signing key (`android_keystore.jks`)
254+1. Build a Signed Android apk for your application
255+1. Deploy the Signed apk to your connected Android device
255256
256−The previous section would have generated a debug version of the app. In order to build a release version you will need to sign your app. Obelisk can automatically sign the app during build if you provide it with your keystore file in `default.nix`.
257+In the event that you change your key or keystore password, you will have to update your credentials within the JSON object found in `android_keytool_config.json`
257258
258−First, if you do not already have a keystore, create it as follows (for more information, see the [Android documentation](https://developer.android.com/studio/publish/app-signing#signing-manually)):
259−
260−```
261−nix-shell -p androidenv.platformTools --run "keytool -genkey -v -keystore myandroidkey.jks -keyalg RSA -keysize 2048 -validity 10000 -alias myandroidalias"
262−```
259+Additional documentation on java key stores can be found [here] (https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html)
263260
264−(Be sure to give an appropriate keystore filename and key alias string above.)
265−
266−The `keytool` command will ask you for some details, including a keystore password and a key password (we will use these passwords further below). It will now have created a `myandroidkey.jks` file under the current directory. Move that to somewhere safe, and note down its full path.
267−
268−Now edit your project's `default.nix` and tell Obelisk of your app's keystore file. Your `default.nix` should look like this after the edit:
261+This should copy over and install the application on your device (if you see a "*signatures do not match*" error, simply uninstall the previous app from the device before retrying the deploy). The name of the installed application will be what you have specified for `android.displayName` in the `default.nix`.
269262
270−```nix
271− ...
272− android.applicationId = "com.example.myapp";
273− android.displayName = "My App";
274− android.releaseKey =
275− { storeFile = /path/to/myandroidkey.jks;
276− storePassword = "abcd1234";
277− keyAlias = "myandroidalias";
278− keyPassword = "abcd1234";
279− };
280− ...
281−```
263+#### Releasing to Play Store
282264
283265##### Build a release version
284266
default.nix+6
@@ -35,6 +35,12 @@ let
3535 (self: super: let
3636 pkgs = self.callPackage ({ pkgs }: pkgs) {};
3737 in {
38+ hnix = pkgs.haskell.lib.dontCheck (self.callCabal2nix "hnix" (pkgs.fetchFromGitHub {
39+ owner = "haskell-nix";
40+ repo = "hnix";
41+ rev = "42afdc21da5d9e076eab57eaa42bfdde938192b8";
42+ sha256 = "0psw384dx9bw2dp93xrzw8rd9amvcwgzn64jzzwby7sfspj6k349";
43+ }) {});
3844 # Need 8.0.2 build support
3945 # PR: https://github.com/dmwit/universe/pull/33
4046 universe-template = self.callCabal2nix "universe-template" (pkgs.fetchFromGitHub {
lib/command/obelisk-command.cabal+2
@@ -23,6 +23,7 @@ library
2323 , github
2424 , here
2525 , hit
26+ , hnix
2627 , hpack
2728 , io-streams
2829 , exceptions
@@ -43,6 +44,7 @@ library
4344 , time
4445 , transformers
4546 , unix
47+ , unordered-containers
4648 , yaml
4749 exposed-modules:
4850 Obelisk.App
lib/command/src/Obelisk/Command.hs+4−8
@@ -142,8 +142,8 @@ deployCommand cfg = hsubparser $ mconcat
142142 ]
143143 where
144144 platformP = hsubparser $ mconcat
145− [ command "android" $ info (pure Android) mempty
146− , command "ios" $ info (pure IOS <*> strArgument (metavar "TEAMID" <> help "Your Team ID - found in the Apple developer portal")) mempty
145+ [ command "android" $ info (pure (Android, [])) mempty
146+ , command "ios" $ info ((,) <$> pure IOS <*> (fmap pure $ strArgument (metavar "TEAMID" <> help "Your Team ID - found in the Apple developer portal"))) mempty
147147 ]
148148
149149 remoteBuilderParser :: Parser (Maybe RemoteBuilder)
@@ -173,16 +173,13 @@ deployInitOpts = DeployInitOpts
173173 <*> flag True False (long "disable-https" <> help "Disable automatic https configuration for the backend")
174174
175175type TeamID = String
176−data PlatformDeployment = Android | IOS TeamID
177− deriving (Show)
178−
179176data RemoteBuilder = RemoteBuilder_ObeliskVM
180177 deriving (Eq, Show)
181178
182179data DeployCommand
183180 = DeployCommand_Init DeployInitOpts
184181 | DeployCommand_Push (Maybe RemoteBuilder)
185− | DeployCommand_Test PlatformDeployment
182+ | DeployCommand_Test (PlatformDeployment, [String])
186183 | DeployCommand_Update
187184 deriving Show
188185
@@ -341,8 +338,7 @@ ob = \case
341338 Nothing -> pure []
342339 Just RemoteBuilder_ObeliskVM -> (:[]) <$> VmBuilder.getNixBuildersArg
343340 DeployCommand_Update -> deployUpdate "."
344− DeployCommand_Test Android -> deployMobile "android" []
345− DeployCommand_Test (IOS teamID) -> deployMobile "ios" [teamID]
341+ DeployCommand_Test (platform, extraArgs) -> deployMobile platform extraArgs
346342 ObCommand_Run -> inNixShell' $ static run
347343 -- inNixShell ($(mkClosure 'ghcidAction) ())
348344 ObCommand_Thunk tc -> case tc of
lib/command/src/Obelisk/Command/Deploy.hs+108−4
@@ -3,23 +3,34 @@
33{-# LANGUAGE OverloadedStrings #-}
44{-# LANGUAGE ScopedTypeVariables #-}
55{-# LANGUAGE ViewPatterns #-}
6+{-# LANGUAGE DeriveGeneric #-}
7+{-# LANGUAGE TypeApplications #-}
68module Obelisk.Command.Deploy where
79
810import Control.Lens
911import Control.Monad
10−import Control.Monad.Catch (Exception (displayException), MonadThrow, throwM, try)
12+import Control.Monad.Catch (Exception (displayException), MonadThrow, throwM, try, bracket_)
1113import Control.Monad.IO.Class (liftIO)
14+import Data.Aeson (FromJSON, ToJSON, encode, eitherDecode)
1215import Data.Bits
16+import qualified Data.ByteString.Lazy as BSL
1317import Data.Default
18+import qualified Data.HashMap.Strict as HM
1419import qualified Data.Map as Map
20+import Data.Text (Text)
1521import qualified Data.Set as Set
1622import qualified Data.Text as T
1723import qualified Data.Text.IO as T
24+import GHC.Generics
25+import Nix.Convert
26+import Nix.Pretty
27+import Nix.Value
1828import System.Directory
1929import System.Environment (getEnvironment)
2030import System.FilePath
31+import System.IO
2132import System.Posix.Files
22−import System.Process (delegate_ctlc, env, proc)
33+import System.Process (delegate_ctlc, env, proc, cwd)
2334import Text.URI (URI)
2435import qualified Text.URI as URI
2536import Text.URI.Lens
@@ -150,13 +161,106 @@ deployPush deployPath getNixBuilders = do
150161deployUpdate :: MonadObelisk m => FilePath -> m ()
151162deployUpdate deployPath = updateThunkToLatest $ deployPath </> "src"
152163
153−deployMobile :: MonadObelisk m => String -> [String] -> m ()
164+keytoolToAndroidConfig :: KeytoolConfig -> HM.HashMap Text (NValueNF Identity)
165+keytoolToAndroidConfig conf = runIdentity $ do
166+ path <- toValue $ Path $ _keytoolConfig_keystore conf
167+ storepass <- toValue $ T.pack $ _keytoolConfig_storepass conf
168+ alias <- toValue $ T.pack $ _keytoolConfig_alias conf
169+ keypass <- toValue $ T.pack $ _keytoolConfig_keypass conf
170+ return $ HM.fromList
171+ [ ("storeFile", path)
172+ , ("storePassword", storepass)
173+ , ("keyAlias", alias)
174+ , ("keyPassword", keypass)
175+ ]
176+
177+data PlatformDeployment = Android | IOS
178+ deriving (Show, Eq)
179+
180+renderPlatformDeployment :: PlatformDeployment -> String
181+renderPlatformDeployment = \case
182+ Android -> "android"
183+ IOS -> "ios"
184+
185+deployMobile :: MonadObelisk m => PlatformDeployment -> [String] -> m ()
154186deployMobile platform mobileArgs = withProjectRoot "." $ \root -> do
155187 let srcDir = root </> "src"
156188 exists <- liftIO $ doesDirectoryExist srcDir
157189 unless exists $ failWith "ob test should be run inside of a deploy directory"
158− result <- nixBuildAttrWithCache srcDir $ platform <> ".frontend"
190+ nixBuildTarget <- case platform of
191+ Android -> do
192+ let keystorePath = root </> "android_keystore.jks"
193+ keytoolConfPath = root </> "android_keytool_config.json"
194+ hasKeystore <- liftIO $ doesFileExist keystorePath
195+ when (not hasKeystore) $ do
196+ -- TODO log instructions for how to modify the keystore
197+ putLog Notice $ "Creating keystore: " <> T.pack keystorePath
198+ putLog Notice "Enter a keystore password: "
199+ keyStorePassword <- liftIO $ withEcho False getLine
200+ putLog Notice "Re-enter the keystore password: "
201+ keyStorePassword' <- liftIO $ withEcho False getLine
202+ unless (keyStorePassword' == keyStorePassword) $ failWith "passwords do not match"
203+ let keyToolConf = KeytoolConfig
204+ { _keytoolConfig_keystore = keystorePath
205+ , _keytoolConfig_alias = "obelisk"
206+ , _keytoolConfig_storepass = keyStorePassword
207+ , _keytoolConfig_keypass = keyStorePassword
208+ }
209+ createKeystore root $ keyToolConf
210+ liftIO $ BSL.writeFile keytoolConfPath $ encode keyToolConf
211+ checkKeytoolConfExist <- liftIO $ doesFileExist keytoolConfPath
212+ unless checkKeytoolConfExist $ failWith "Missing android KeytoolConfig"
213+ keytoolConfContents <- liftIO $ BSL.readFile keytoolConfPath
214+ liftIO $ putStrLn $ show keytoolConfContents
215+ releaseKey <- case eitherDecode keytoolConfContents of
216+ Left err -> failWith $ T.pack err
217+ Right conf -> do
218+ let nvset = toValue @(HM.HashMap Text (NValueNF Identity)) @Identity @(NValueNF Identity) $ keytoolToAndroidConfig conf
219+ return $ printNix $ runIdentity nvset
220+ return $ Target
221+ { _target_path = Nothing
222+ , _target_attr = Nothing
223+ , _target_expr = Just $ "with (import " <> srcDir <> " {}); " <> renderPlatformDeployment platform <> ".frontend.override (drv: { releaseKey = (if builtins.isNull drv.releaseKey then {} else drv.releaseKey) // " <> releaseKey <> "; })"
224+ }
225+ IOS -> return $ Target
226+ { _target_path = Nothing
227+ , _target_attr = Just "ios.frontend"
228+ , _target_expr = Nothing
229+ }
230+ result <- nixCmd $ NixCmd_Build $ def
231+ & nixBuildConfig_outLink .~ OutLink_None
232+ & nixCmdConfig_target .~ nixBuildTarget
233+ putLog Notice $ T.pack $ "Your recently built android apk can be found at the following path: " <> (show result)
159234 callProcessAndLogOutput (Notice, Error) $ proc (result </> "bin" </> "deploy") mobileArgs
235+ where
236+ withEcho showEcho f = do
237+ prevEcho <- hGetEcho stdin
238+ bracket_ (hSetEcho stdin showEcho) (hSetEcho stdin prevEcho) f
239+
240+data KeytoolConfig = KeytoolConfig
241+ { _keytoolConfig_keystore :: FilePath
242+ , _keytoolConfig_alias :: String
243+ , _keytoolConfig_storepass :: String
244+ , _keytoolConfig_keypass :: String
245+ } deriving (Show, Generic)
246+
247+instance FromJSON KeytoolConfig
248+instance ToJSON KeytoolConfig
249+
250+createKeystore :: MonadObelisk m => FilePath -> KeytoolConfig -> m ()
251+createKeystore root config = do
252+ let expr = "with (import " <> toImplDir root <> ").reflex-platform.nixpkgs; pkgs.mkShell { buildInputs = [ pkgs.jdk ]; }"
253+ callProcessAndLogOutput (Notice,Notice) $ (proc "nix-shell" ["-E" , expr, "--run" , keytoolCmd]) { cwd = Just root }
254+ where
255+ keytoolCmd = processToShellString "keytool"
256+ [ "-genkeypair", "-noprompt"
257+ , "-keystore", _keytoolConfig_keystore config
258+ , "-keyalg", "RSA", "-keysize", "2048"
259+ , "-validity", "1000000000"
260+ , "-storepass", _keytoolConfig_storepass config
261+ , "-alias", _keytoolConfig_alias config
262+ , "-keypass", _keytoolConfig_keypass config
263+ ]
160264
161265-- | Simplified deployment configuration mechanism. At one point we may revisit this.
162266writeDeployConfig :: MonadObelisk m => FilePath -> FilePath -> String -> m ()
lib/command/src/Obelisk/Command/Nix.hs+1
@@ -180,3 +180,4 @@ nixCmd cmdCfg = withSpinner' ("Running " <> cmd <> desc) (Just $ const $ "Built
180180 [ (" on " <>) <$> path
181181 , (\a -> " [" <> a <> "]") <$> (commonCfg ^. nixCmdConfig_target . target_attr)
182182 ]
183+