Category: Coding & Scripting

Create certificate for localhost domains on macOS

Step 1: create a self-signed root certificate

First, let’s create a self-signed root certificate:

openssl req -x509 -nodes -new -sha256 -days 390 -newkey rsa:2048 -keyout "RootCA.key" -out "RootCA.pem" -subj "/C=de/CN=localhost.local"
openssl x509 -outform pem -in "RootCA.pem" -out "RootCA.crt"

The parameter -days 390 sets the number of days, this certificate is valid. Starting on September 1st (2020), SSL/TLS certificates cannot be issued for longer than 13 months (397 days), see https://stackoverflow.com/a/65239775.

If this time is too long, you will receive an NET::ERR_CERT_VALIDITY_TOO_LONG error. In the command above, this value was set to 390 days, which works for me.

Step 2: define domains and subdomains that should be included in the certificate

For this, just create a text file named vhosts_domains.ext and insert the following contents:

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
DNS.2 = *.mixable.blog.local
DNS.3 = mixable.blog.local

This example includes subdomains for a local development environment for the domain mixable.blog.local and all subdomains like www.mixable.blog.local or apps.mixable.blog.local.

If you plan to use a more general certificate e.g. to include all subdomains under *.*.blog.local, this will not work. The definition only supports ‘first level’ subdomains. It would be great, because this saves a lot of additional setup, but unfortunately this is note supported.

Step 3: create the certificate

Now let’s create the certificate:

openssl req -new -nodes -newkey rsa:2048 -keyout localhost.key -out localhost.csr -subj "/C=de/ST=State/L=City/O=Organization/CN=localhost.local"
openssl x509 -req -sha256 -days 1024 -in localhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile vhosts_domains.ext -out localhost.crt

Calling the two commands above will create the localhost certificate that includes all the provided domains and subdomains. Your file listing should look like this:

Step 4: make the certificate available for Apache

Depending on your system, copy all those files into the the configuration folder of the Apache installation. In my case, the installation was done with the help of brew, so the local path is:

/usr/local/etc/httpd/cert/

At the end, it’s not important where those files are located, because we no add this path to the vhost definitions. For this, open your vhosts file and link the crt and the key file as follows:

# mixable.blog.local
<VirtualHost *:80>
    ServerAdmin webmaster@example.com
    DocumentRoot "/Users/mathias/Sites/mixable.blog.local"
    ServerName mixable.blog.local
    ServerAlias mixable.blog.local
    ErrorLog "/usr/local/var/log/httpd/localhost-error.log"
    CustomLog "/usr/local/var/log/httpd/localhost-access.log" common
</VirtualHost>
<VirtualHost *:443>
    DocumentRoot "/Users/mathias/Sites/mixable.blog.local"
    ServerName mixable.blog.local
    SSLEngine on
    SSLCertificateFile "/usr/local/etc/httpd/cert/localhost.crt"
    SSLCertificateKeyFile "/usr/local/etc/httpd/cert/localhost.key"
</VirtualHost>

If you have additional vhost definitions, you can add the <VirtualHost *:443> part to every server name entry and use the correct paths to SSLCertificateFile and SSLCertificateKeyFile.

After changing the vhost settings, it is required to restart your Apache server!

Step 5: add the certificates to macOS

When opening a local website, the certificate should be used but you might see a NET::ERR_CERT_INVALID error. This is the case, because modern browsers/systems do not trust self-signed certificates by default. to overcome this issue, we have to add the created certificates to the macOS Keychain Access. For this, open the *.crt files in Keychain Access:

So that they are know by macOS:

And finally, update the trust settings of each certificate to “Always trust”:

You should now be able to use a secure connection between your browser and your local server:

Step 6: additional fixes

The steps above might already work for Chrome and Safari. If you have problems with Firefox, just open settings and go to Privacy & Security. Then you have to import the root certificate file RootCA.crt, so that Firefox knows about your certificate.

UX improvements: `enterkeyhint` to define action label for the keyboard of mobile devices

Usability

The enterkeyhint is a html attribute described in the HTML standard, which can be used to improve the context of action buttons of keyboards on mobile device.

The enterkeyhint content attribute is an enumerated attribute that specifies what action label (or icon) to present for the enter key on virtual keyboards. This allows authors to customize the presentation of the enter key in order to make it more helpful for users.

It allows the following fixed values: enter, done, go, next, previous, search and send. Let’s have a look at those values and the resulting keyboard style on iOS:

<input>

The default behavior without any value.

<input enterkeyhint=”enter”>

The user agent should present a cue for the operation ‘enter’, typically inserting a new line.

<input enterkeyhint=”done”>

The user agent should present a cue for the operation ‘done’, typically meaning there is nothing more to input and the input method editor (IME) will be closed.

<input enterkeyhint=”go”>

The user agent should present a cue for the operation ‘go’, typically meaning to take the user to the target of the text they typed.

<input enterkeyhint=”next”>

The user agent should present a cue for the operation ‘next’, typically taking the user to the next field that will accept text.

<input enterkeyhint=”previous”>

The user agent should present a cue for the operation ‘previous’, typically taking the user to the previous field that will accept text.

<input enterkeyhint=”search”>

The user agent should present a cue for the operation ‘search’, typically taking the user to the results of searching for the text they have typed.

<input enterkeyhint=”send”>

The user agent should present a cue for the operation ‘send’, typically delivering the text to its target.

Photo by Melisa Hildt on Unsplash

Flutter on iOS: themeMode does not change to dark mode if `ThemeMode.system` is used

In my case, a simple app should automatically use the theme (light or dark) of the system to style the user interface. By default, this should work when using ThemeMode.system (see flutter documentation). But it didn’t.

The themes have been defined as follows:

    return MaterialApp(
      themeMode: ThemeMode.system,
      theme: ThemeData( ... ),
      darkTheme: ThemeData( ...),
      ...
    );

In addition, the WidgetsBindingObserver callback didChangePlatformBrightness() was never called. It was defined as follows:

class MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver
{
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangePlatformBrightness() {
    print(WidgetsBinding.instance.window.platformBrightness);
    // > should print Brightness.light / Brightness.dark when you switch
    super.didChangePlatformBrightness();
  }
}

After hours and days of searching, it turned out, that the following definition was set in info.plist of iOS:

<key>UIUserInterfaceStyle</key>
<string>Light</string>

Removing this line solved the issue. This setting sets the apps theme to Light, which results in a constant value even if the user changed the brightness to dark. Without this line, UIUserInterfaceStyle depends on the global setting.

Source: https://stackoverflow.com/questions/61620332/platform-brightness-is-still-light-on-ios-even-when-dark-mode-is-on-flutter

fatal error: ‘Flutter/Flutter.h’ file not found

After switching the flutter channel to beta and back to stable, my app did not compile anymore. The compilation stopped with the error:

fatal error: 'Flutter/Flutter.h' file not found

Multiple flutter clean and channel switches did not work in this case.

The following commands fixed this behavior:

rm ios/Flutter/Flutter.podspec
flutter clean

See: https://github.com/flutter/flutter/issues/70895#issuecomment-744734693

Swift: how to create a Singleton pattern

What is a Singleton?

A singleton pattern guarantees that only one instance of a class is initialized and available from different points of an app.

Some examples are already available in Apple’s frameworks:

// Shared URL Session
let sharedURLSession = URLSession.shared

// Default File Manager
let defaultFileManager = FileManager.default

// Standard User Defaults
let standardUserDefaults = UserDefaults.standard

How to define a Singleton

Often a static constant is used to adopt the Singleton pattern. To do that the reference to the shared instance is stored inside a static constant. In addition, the initializer is private and therefore hidden:

class NetworkManager {
    static let sharedInstance = NetworkManager()

    private init() { }

    func doSomething() {
        // ...
    }
}

By making the initializer method private, it’s guaranteed that no other instance of this class can be created. It would also be possible to move the static constant outside the class, but then the initializer might be accessible and that’s not what we want.

To access our NetworkManager instance just call:

NetworkManager.sharedInstance.doSomething()
NetworkManager.sharedInstance.doSomething()

This approach allows to use always the same instance, even in different points of the app.

PHPUnit: faster and better unit tests with pcov

When using PHPUnit there are different ways to create a code coverage report. By default, XDebug is used. But as mention on different sites, XDebug is very slow and the generation of a code coverage report might take several minutes for big projects.

phpdbg

To speed up things, phpdbg can be used. This significantly speeds up unit tests and code coverage. Phpdbg can be used as follows:

phpdbg -qrr ./vendor/bin/phpunit --coverage-text --colors=never

But there are different problems with the code coverage report of phpdbg. For example phpdbg does not cover a case line of a switch statement:

pcov

A better solution to cover this is pcov, which can be installed using pecl:

pecl install pcov

To create a code coverage report, phpunit can be called with:

php -dpcov.enabled=1 -dpcov.directory=. ./vendor/bin/phpunit --coverage-text

To exclude a directory, the following parameter can be used:

php -dpcov.enabled=1 -dpcov.directory=.  -dpcov.exclude="~vendor~" ./vendor/bin/phpunit --coverage-text

I don’t know if it’s really a problem with pcov, but: with pcov installed, it is not possible to use phpdbg anymore!

PHP: realpath() for non-existing path

The php method realpath() can transform the string format of a path into a real path. Means, a path string like:

/Users/mathias/data/../projects/website

will become:

/Users/mathias/projects/website

But this only works, if the path really exists. For non-existing paths, this function cannot be used. To get the same functionality, the following function can be used:

/**
 * Get normalized path, like realpath() for non-existing path or file
 *
 * @param string $path path to be normalized
 * @return false|string|string[]
 */
public function normalizePath(string $path)
{
    return array_reduce(explode('/', $path), function($a, $b) {
        if ($a === null) {
            $a = "/";
        }
        if ($b === "" || $b === ".") {
            return $a;
        }
        if ($b === "..") {
            return dirname($a);
        }

        return preg_replace("/\/+/", "/", "$a/$b");
    });
}

How to ignore PHP_CodeSniffer warning: Line exceeds 120 characters;

When using codesniffer to check your code, a lot of warnings might appear when the lines are too long:

----------------------------------------------------------------------
FOUND 0 ERRORS AND 4 WARNINGS AFFECTING 4 LINES
----------------------------------------------------------------------
  73 | WARNING | Line exceeds 120 characters; contains 162 characters
  75 | WARNING | Line exceeds 120 characters; contains 124 characters
 102 | WARNING | Line exceeds 120 characters; contains 168 characters
 108 | WARNING | Line exceeds 120 characters; contains 121 characters
----------------------------------------------------------------------

To ignore those warnings, we can add // phpcs:ignore as a comment to the end of a (too long) line. For example:

<?php
$message = 'This is my long message. It\'s not only long, it\'s extreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeemly long'; // phpcs:ignore